83. Remove Duplicates from Sorted List

问题
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

设置前一个节点和当前节点两个指针。
由于是有数的链表,遍历时可以直接比较两个节点。
如相等则前一个节点的next指向当前节点的next。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {

if ( head == null){
return head;
}
if ( head.next == null){
return head;
}
ListNode prev = head;
ListNode curr = head.next;

while(curr != null){
if(prev.val != curr.val){
curr = curr.next;
prev = prev.next;
}
else{
prev.next = curr.next;
curr = curr.next;
}
}
return head;
}
}
Author

Xander

Posted on

2022-04-10

Updated on

2022-04-09

Licensed under

Comments