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
.
问题描述:给定一个有序链表,删除重复的,使得链表每个元素只出现一次。
分析:将链表的后一个元素与前一个元素比较,如果两元素相等,则另该链表的前一个元素next指针指向后一个元素的next指针;如果不相等则将next指针后移,直到next指针为空。
/**
* 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)
return null;
ListNode p = head;
ListNode q = head.next;
while(q!=null){
if(q.val == p.val){
p.next = q.next;
q = q.next;
}else{
p = p.next;
q = q.next;
}
}
return head;
}
}