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
.
刪除有序鏈表中重複的數值,一次遍歷,設置指針指定第一次出現的數值,一直到該數值消失(或者鏈表到頭),刪除中間的所有重複值。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null)return head;
ListNode p=head,q=head;
int num=head.val;
while(p!=null)
{
if(p.val!=num && p!=q)
{
num=p.val;
q.next=p;
q=p;
}
p=p.next;
}
if(p!=q)q.next=null;
return head;
}
}