剑指offer--链表

题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        res = []
        while listNode != None:
            res.append(listNode.val)
            listNode = listNode.next
        return res[::-1]

题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        # write code here
        dict1 = {}
        while pHead != None:
            if pHead.val not in dict1:
                dict1[pHead.val] = 1
            else:
                return pHead
            pHead = pHead.next

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

# -*- 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(0)
        head.next = pHead
        pre = head
        last = head.next
        while pre and last:
            if last.next and (last.next.val == last.val):
                while last.next and (last.next.val == last.val):
                    last = last.next
                pre.next = last.next
                last = last.next
            else:
                pre = pre.next
                last = last.next
        return head.next
发布了9 篇原创文章 · 获赞 0 · 访问量 755

猜你喜欢

转载自blog.csdn.net/weixin_42707571/article/details/105255464