203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

很浅显易懂的问题,遇到不同的就删,同样的就下一个。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* removeElements(struct ListNode* head, int val) {
 9     if(!head)   return NULL;
10     struct ListNode *delete=head;
11     struct ListNode *n=head;
12     while(n){
13         if(head->val==val){
14             head=head->next;
15         }
16         else if(n->val==val){
17             delete->next=n->next;
18             n=n->next;
19             continue;
20         }
21         delete=n;
22         n=n->next;
23     }
24     return head;
25 }

 

posted @ 2018-10-31 00:03  杜王町上班族  阅读(141)  评论(0)    收藏  举报