首页 > 其他 > 详细

LeeCode-Remove Linked List Elements

时间:2015-07-20 10:46:44      阅读:98      评论:0      收藏:0      [点我收藏+]

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

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 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 {
10         if(head==NULL)
11         return NULL;
12     
13     if(head->next==NULL&&head->val==val)
14     {
15         return NULL;
16     }
17 
18     if(head->next==NULL&&head->val!=val)
19     {
20         return head;
21     }
22 
23 
24     
25     struct ListNode *p=head;
26     
27     while(p->val==val&&p->next!=NULL)
28     {
29         p=p->next;
30     }
31     
32     if(p->val==val)
33     {
34         return NULL;
35     }
36     
37     
38     head=p;
39     
40     if(p->next==NULL)
41     {
42         return head;
43     }
44 
45     while(p->next->next!=NULL)
46     {
47         if(p->next->val==val)
48         {
49             p->next=p->next->next;
50             continue;
51         }
52         p=p->next;
53     }
54     
55     if(p->next->val==val)
56     {
57         p->next=NULL;
58     }
59     
60     return head;
61 }

 

LeeCode-Remove Linked List Elements

原文:http://www.cnblogs.com/vpoet/p/4660542.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!