题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路
实现原理都是删除重复的Node结点
递归
非递归
图解如下
非递归的代码实现
// 非递归
public class Solution {
public ListNode deleteDuplication(ListNode pHead){
ListNode q,p,r;
p = pHead;
q = r = null;
while (p != null){
boolean flag = false;
r = p.next;
while (r != null && r.val == p.val){
flag = true;
r = r.next;
}
if (flag){
if (q != null){
q.next = r;
}else {
pHead = null;
}
}else {
if (q == null){
pHead = p;
}
q = p;
}
p = r;
}
return pHead;
}
}
递归代码实现
// 递归
public ListNode deleteDuplication(ListNode pHead) {
// 只有0个或1个结点,则返回
if (pHead == null || pHead.next == null) {
return pHead;
}
// 当前结点是重复结点
if (pHead.val == pHead.next.val) {
ListNode pNode = pHead.next;
while (pNode != null && pNode.val == pHead.val) {
// 跳过值与当前结点相同的全部结点,找到第一个与当前结点不同的结点
pNode = pNode.next;
}
// 从第一个与当前结点不同的结点开始递归
return deleteDuplication(pNode);
} else { // 当前结点不是重复结点
// 保留当前结点,从下一个结点开始递归
pHead.next = deleteDuplication(pHead.next);
return pHead;
}
}
NowCoder(Online Coding, Please Click)