剑指Offer题目:删除链表中重复的结点
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
解题思路
思路:利用双指针,首先建立一个虚拟头结点vroot
,然后设置两个指针pre
和cur
pre
指向确定不会重复的结点,cur
作为工作指针不断向后搜索。最后结果返回vroot
的下一结点。
完整代码
public class q57_deleteDuplication_删除链表中重复的结点 {
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null) return pHead;
ListNode vroot = new ListNode(-1);
vroot.next = pHead;
ListNode pre = vroot;
ListNode cur = pHead;
while (cur != null) {
//有元素重复
if (cur.next != null && cur.next.val == cur.val) {
//向后搜索,直到链表末尾或者和下一个元素不相等
while (cur.next != null && cur.next.val == cur.val) {
cur = cur.next;
}
//将pre指针指向cur的下一元素,该元素确定不会和它的前驱结点元素相等
pre.next = cur.next;
cur = cur.next;
}
//当前结点为链表末尾结点或者当前元素和下一元素不相等,当前结点就是唯一的结点
else {
//pre指针指向该元素,并继续向下查找
pre.next = cur;
pre = pre.next;
cur = cur.next;
}
}
return vroot.next;
}
}
更多LeetCode题目及答案解析见GitHub: https://github.com/on-the-roads/LeetCode
剑指offer题目及答案解析:https://github.com/on-the-roads/SwordToOffer