Leetcode Algorithms-83.Remove Duplicates from Sorted List

问题地址

Remove Duplicates from Sorted List - LeetCode

问题描述

0.jpg

解法

非递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {

public ListNode deleteDuplicates(ListNode head) {
if (null == head) return head;
ListNode tail = head;
ListNode now = head.next;
while (null != now) {
if (tail.val != now.val) {
tail.next = now;
tail = now;
}
now = now.next;
}
tail.next = null;
return head;
}
}

class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {

public ListNode deleteDuplicates(ListNode head) {
if(null == head || null == head.next) return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
}

class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
0%