203. 移除链表元素(简单)
struct ListNode* removeElements(struct ListNode* head, int val){
typedef struct ListNode ListNode;
ListNode*dummyHead =(ListNode*)malloc(sizeof(ListNode));
dummyHead->val=0;
dummyHead->next=head;
ListNode*p=dummyHead;//遍历节点
while(p->next!=NULL){
if(p->next->val==val){
ListNode*tmp=p->next;
p->next=p->next->next;
free(tmp);
}
else
p=p->next;//要么删除,要么移动
}
head=dummyHead->next;
free(dummyHead);
return head;
}
206. 反转链表
双指针法
struct ListNode* reverseList(struct ListNode* head){
typedef struct ListNode ListNode;
ListNode*tmp;//用于临时保存
ListNode*cur=head;
ListNode*pre=NULL;//记录的是反转后链表的头结点
while(cur!=NULL){
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
- 头插法反转链表是对空间的浪费
- 这一题的递归写法需要重新看