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;
}
}