LeetCode OJ :Remove Linked List Elements (移除链表元素)
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
ps:这一题感觉没什么技巧可言,选取一个头指针,一个当前指针,一个前向指针。简单的链表操作而已,代码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 ListNode * root = head; 13 ListNode * prev = head; 14 ListNode * curr = head; 15 while (curr != NULL){ 16 if (curr->val == val){ 17 if (prev == curr) 18 root = prev = curr = curr->next; 19 else{ 20 curr = curr->next; 21 prev->next = curr; 22 } 23 }else{ 24 prev = curr; 25 curr = curr->next; 26 } 27 } 28 return root; 29 } 30 };
java版本如下所示:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode removeElements(ListNode head, int val) { 11 while(head != null && head.val == val){ 12 ListNode helper = head; 13 head = head.next; 14 helper.next = null; 15 } 16 if(head == null) 17 return head; 18 ListNode p1 = head; 19 while(p1.next != null){ 20 if(p1.next.val == val){ 21 p1.next = p1.next.next; 22 }else 23 p1 = p1.next; 24 } 25 return head; 26 } 27 }