原创

【剑指Offer】056——删除链表中重复的结点 (链表)

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

解题思路

  1. 首先添加一个头节点,以方便碰到第一个,第二个节点就相同的情况
  2. 设置 first ,second 指针, first 指针指向当前确定不重复的那个节点,而second指针相当于工作指针,一直往后面搜索。
    file

参考代码

Java

/*
 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 head = new ListNode(-1);
        head.next = pHead;// 把新头节点放在链表最前,构成新得链表
        ListNode first = head;
        ListNode second = first.next;
        // 开始从头遍历
        while(second != null){
            if(second.next != null && second.val == second.next.val){
                // 找到不相等得结点
                while(second.next != null && second.val == second.next.val){
                    second = second.next;
                }
                first.next = second.next;
            }else{
                first = first.next;
            }
            second = second.next;
        }
        return head.next;
    }
}

Python

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        head = ListNode(-1)
        head.next = pHead
        first = head
        second = first.next
        while second:
            if second.next and second.val == second.next.val:
                while second.next and second.val == second.next.val:
                    second = second.next
                first.next = second.next
            else:
                first = first.next
            second = second.next
        return head.next
正文到此结束
本文目录