首页 > 代码库 > LeetCode 203 Remove Linked List Elements

LeetCode 203 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

 

思路:

主要就是遍历链表,发现结点的值与要求的值相等的时候即可删除结点。这道题应该注意一下边界条件。

 

解法:

1.在头节点之前申请一个额外结点,这样就可以利用双指针进行删除的操作,比较方便。

 1 /* 2     public class ListNode 3     { 4         int val; 5         ListNode next; 6  7         ListNode(int x) 8         { val = x; } 9     }10 */11 12 public class Solution13 {14     public ListNode removeElements(ListNode head, int val)15     {16         ListNode extraNode = new ListNode(0);17         extraNode.next = head;18 19         ListNode front = head;20         ListNode behind = extraNode;21 22         while(front != null)23         {24             if(front.val == val)25                 behind.next = front.next;26             else27                 behind = behind.next;28             front = front.next;29         }30 31         return extraNode.next;32     }33 }

 

2.不申请先于头结点的结点,以常规的方式进行遍历,这种方法需要注意边界条件。

 1 /* 2     public class ListNode 3     { 4         int val; 5         ListNode next; 6  7         ListNode(int x) 8         { val = x; } 9     }10 */11 12 public class Solution13 {14     public ListNode removeElements(ListNode head, int val)15     {16         ListNode flag = head;17 18         while(true)19         {20             if(head == null)21                 return null;22             if(flag.val != val)23                 break;24             flag = flag.next;25             head = flag;26         }27 28         while(flag.next != null)29         {30             if(flag.next.val == val)31                 flag.next = flag.next.next;32             else33                 flag = flag.next;34         }35 36         return head;37     }38 }

 

LeetCode 203 Remove Linked List Elements