Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
题目分析:两个指针O(n)扫一下
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
ListNode nxt = head.next;
while (nxt != null) {
while (nxt != null && cur.val == nxt.val) {
nxt = nxt.next;
}
if (nxt != null) {
cur.next = nxt;
cur = nxt;
nxt = nxt.next;
}
cur.next = null;
}
return head;
}
}
更简单的实现方式:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while (cur != null) {
if (cur.next == null) {
return head;
}
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}