LeetCode 203. Remove Linked List Elements

原题链接:https://leetcode.com/problems/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

题解:

建一个dunmy,dunmy.next = head,为了防止head.val 等于要被去掉的value时删掉head不方便表示。

Time Complexity: O(n), n是list长度. Space: O(1).

AC 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         if(head == null){
12             return head;
13         }
14         
15         ListNode dummy = new ListNode(0);
16         dummy.next = head;
17         ListNode cur = dummy;
18         while(cur.next != null){
19             if(cur.next.val == val){
20                 cur.next = cur.next.next;
21             }else{
22                 cur = cur.next;
23             }
24         }
25         return dummy.next;
26     }
27 }

Recursion Method, stop condition 是 head == null, return head. 

Time Complexity: O(n), n 是list长度. Space: O(n), stack space.

AC 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         if(head == null){
12             return head;
13         }
14         head.next = removeElements(head.next, val);
15         return head.val == val ? head.next : head;
16     }
17 }

类似Delete Node in a Linked List.

posted @ 2015-08-23 00:14  Dylan_Java_NYC  阅读(178)  评论(0编辑  收藏  举报