剑指Offer_刷题Day2

剑指Offer_刷题Day2

状态不好,只做了两道题,有一题题意没有理解,下次再修改吧

Q1:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null

思路

  • 使用一个列表存储已经访问过的点

Code

python

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        # write code here
        visited=[]
        p=pHead
        while p!=None:
            if p in visited:
                return p
            visited.append(p)
            p=p.next
        return None

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

思路

  • 我只是去重,没有删除所有的,仍然保留了一个

Code

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 pHead==None:
            return None
        p1,p2=pHead,pHead.next
        while p1!=None:
            while p2!=None and p1.val==p2.val:
                p2=p2.next
                #print(p1.val,p2.val)
            p1.next=p2
            p1=p1.next
            if p2==None:
                break
            else:
                p2=p2.next
        return pHead

猜你喜欢

转载自blog.csdn.net/weixin_43982484/article/details/89706045