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 || head.next == null)
return head;
ListNode p = head,q = p.next;
int tmp;
while(q != null)
{
tmp = p.val;
if(q.val == tmp)
{
q = q.next;
if(q == null)
p.next = null;
}
else
{
p.next = q;
p = q;
q = p.next;
}
}
return head;
}
}