题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表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)
{
if(pHead == null || pHead.next == null) {
return pHead;
}
if(pHead.next.val == pHead.val) {
ListNode curNode = pHead.next.next;
int val = pHead.val;
while(curNode != null && curNode.val == val) {
curNode = curNode.next;
}
return deleteDuplication(curNode);
} else {
pHead.next = deleteDuplication(pHead.next);
return pHead;
}
}
}
解法二:非递归
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead == null || pHead.next == null) {
return pHead;
}
ListNode root = new ListNode(0);
root.next = pHead;//头结点前驱结点
ListNode pre = root;//pre为移动当前节点的前驱节点
ListNode cur = pHead;//当前节点
while(cur != null && cur.next != null) {
//当前节点与下一个节点值相等
if(cur.next.val == cur.val) {
while(cur.next != null && cur.next.val == cur.val) {
cur = cur.next;
}
//pre不需后移,因为node.next也可能是重复的
pre.next = cur.next;
}
//当前节点与下一节点
else {
pre.next = cur;
pre = pre.next;
}
cur = cur.next;
}
return root.next;
}
}