链表 ---java

pHead问题
1、默认头结点就是首节点
pHead == null || pHead.next == null 表示只有0个或1个结点
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。```
//默认头结点就是首节点
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null) { // 只有0个或1个结点,则返回
return pHead;
}
ListNode pNode = pHead.next;
if (pHead.val == pNode.val) { // 当前结点是重复结点
while (pNode != null && pNode.val == pHead.val) {
// 跳过值与当前结点相同的全部结点,找到第一个与当前结点不同的结点
pNode = pNode.next;
}
return deleteDuplication(pNode); // 从第一个与当前结点不同的结点开始递归
} else { // 当前结点不是重复结点
pHead.next = deleteDuplication(pNode); // 保留当前结点,从下一个结点开始递归
}
return pHead;
}


猜你喜欢

转载自blog.csdn.net/ZJKL_Silence/article/details/88144905
今日推荐