Remove Linked List Elements
Description:
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
Code1:
1 ListNode* removeElements(ListNode* head, int val) { 2 if (head==NULL) 3 { 4 return NULL; 5 } 6 7 //在链表两端分别插入头结点和尾结点 8 ListNode* headNode = new ListNode(0); 9 headNode->next = head; 10 11 ListNode* q = headNode; 12 while (q->next) 13 { 14 q = q->next; 15 } 16 ListNode* tailNode = new ListNode(0); 17 q->next = tailNode; 18 19 q = head; 20 ListNode* preNode = headNode;//指向被删结点的上一个结点 21 while (q!=tailNode) 22 { 23 if (q->val == val) 24 { 25 preNode->next = q->next; 26 delete q; 27 q = preNode->next; 28 } 29 else 30 { 31 q=q->next; 32 preNode=preNode->next; 33 } 34 } 35 36 if (headNode == tailNode) 37 return NULL; 38 else 39 { 40 preNode->next = NULL; 41 head = headNode->next; 42 delete headNode; 43 delete tailNode; 44 return head; 45 } 46 }
Code2:
1 ListNode* removeElements(ListNode* head, int val) { 2 if (head==NULL) 3 { 4 return NULL; 5 } 6 7 ListNode* q = head; 8 ListNode* preNode = NULL;//指向被删结点的上一个结点 9 while (q!=NULL) 10 { 11 if (q->val == val) 12 { 13 if (q == head) 14 { 15 head = head->next; 16 delete q; 17 q = head; 18 } 19 else 20 { 21 preNode->next = q->next; 22 delete q; 23 q = preNode->next; 24 } 25 } 26 else 27 { 28 preNode = q; 29 q=q->next; 30 } 31 } 32 return head; 33 }