题目描述:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
思路一:
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
ListNode first = new ListNode(-1);
first.next = pHead;
ListNode p = pHead;
ListNode last = first;
while (p != null && p.next != null)
{
if (p.val == p.next.val)
{
int val = p.val;
while (p != null && p.val == val)
p = p.next;
last.next = p;
}
else
{
last = p;
p = p.next;
}
}
return first.next;
}
}
思路二:递归
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if (pHead == null || pHead.next == null)
return pHead;
if (pHead.val == pHead.next.val)
{
ListNode p = pHead.next.next;
while (p != null && p.val == pHead.val)
p = p.next;
return deleteDuplication(p);
}
else
{
pHead.next = deleteDuplication(pHead.next);
return pHead;
}
}
}