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.
给定一个排好序的链表,删除所有重复的元素。
算法分析
本题重点在给定的链表已经排序,因此只要从头开始删除重复的元素即可,即current.val == current.next.next
,就删除,current.next = current.next.next
。
Java代码
/**
* 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 current = head;
while (current != null && current.next != null) {//
if (current.val != current.next.val) {
current = current.next;
} else {
current.next = current.next.next;
}
}
return head;
}
}