代码随想录算法训练营第四天| 24. 两两交换链表中的节点 、19.删除链表的倒数第N个节点 、 面试题 02.07. 链表相交 、 142.环形链表II

第一题 两两交换链表中的节点

题目描述:
   给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
思路:
   具体代码如下:

from typing import Optional, List

class ListNode:
    def __init__(self, val=0, next = None):
        self.val = val
        self.next = next

    def __repr__(self):
        return str(self.val)

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
    	if head is None:
    		return None

    	current = head.next

    	if current:
    		tmp = current.next
    		current.next = head
    		head.next = self.swapPairs(tmp)
    	else:
    		return head
    	
    	return current

def nums2List(nums: List[int]):
	res = ListNode(nums[0])
	previous = res

	for i in range(1, len(nums)):
		tmp = ListNode(nums[i])
		previous.next = tmp
		previous = tmp

	return res

def printList(head: Optional[ListNode]):

	while head :
		print(head, end =' ')
		head = head.next
		
	print()

if __name__ == '__main__':
    solution = Solution()
    res = nums2List([1,2,3,4])
    printList(res)
    printList(solution.swapPairs(res)) 

第二题 删除链表的倒数第 N 个结点

题目描述:
   给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
思路:
   具体代码如下:

from typing import Optional, List

class ListNode:
    def __init__(self, val=0, next = None):
        self.val = val
        self.next = next

    def __repr__(self):
        return str(self.val)

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy_head = ListNode(next = head)
        fast = head
        i = 0

        while i < n and fast:
            fast = fast.next
            i += 1

        pre = dummy_head

        while fast:
            pre = pre.next
            fast = fast.next

        pre.next = pre.next.next

        return dummy_head.next

def nums2List(nums: List[int]):
    res = ListNode(nums[0])
    previous = res

    for i in range(1, len(nums)):
        tmp = ListNode(nums[i])
        previous.next = tmp
        previous = tmp

    return res

def printList(head: Optional[ListNode]):

    while head :
        print(head, end =' ')
        head = head.next
        
    print()

if __name__ == '__main__':
    solution = Solution()
    res = nums2List([1,2,3,4])
    printList(res)
    printList(solution.removeNthFromEnd(res, 1)) 

第三题 链表相交

题目描述:
   给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
思路:
   具体代码如下:

from typing import Optional, List

class ListNode:
    def __init__(self, val=0, next = None):
        self.val = val
        self.next = next

    def __repr__(self):
        return str(self.val)

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB:
            return None

        pointerA = headA
        pointerB = headB

        while pointerA != pointerB:
            pointerA = pointerA.next if pointerA else headB
            pointerB = pointerB.next if pointerB else headA

        return pointerA


def nums2List(nums: List[int]):
    res = ListNode(nums[0])
    previous = res

    for i in range(1, len(nums)):
        tmp = ListNode(nums[i])
        previous.next = tmp
        previous = tmp

    return res

def listIntersect(headA: Optional[ListNode], headB: Optional[ListNode], headSame: Optional[ListNode]):
    previousA = headA 
    previousB = headB

    while previousA.next:
        previousA = previousA.next

    while previousB.next:
        previousB = previousB.next

    previousA.next = headSame
    previousB.next = headSame

def printList(head: Optional[ListNode]):

    while head :
        print(head, end =' ')
        head = head.next
        
    print()

if __name__ == '__main__':
    solution = Solution()
    resA = nums2List([4,1])
    resB = nums2List([5,0,1])
    same = nums2List([8,4,5])
    listIntersect(resA, resB, same)
    printList(resA)
    printList(resB)
    printList(solution.getIntersectionNode(resA, resB)) 

第四题 环形链表 II

题目描述:
   给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
思路:
   具体代码如下

from typing import Optional, List

class ListNode:
    def __init__(self, val=0, next = None):
        self.val = val
        self.next = next

    def __repr__(self):
        return str(self.val)

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:

    	slow, fast = head, head

    	while fast and fast.next:
    		slow = slow.next
    		fast = fast.next.next

    		if slow == fast:
    			slow = head

    			while slow != fast:
    				slow = slow.next
    				fast = fast.next
    			return slow

    	return None

def nums2List(nums: List[int]):
    res = ListNode(nums[0])
    previous = res

    for i in range(1, len(nums)):
        tmp = ListNode(nums[i])
        previous.next = tmp
        previous = tmp

    return res

def createCycle(head: Optional[ListNode], val: int):
	previous = head

	while head.next:
		if head.val == val:
			previous = head
		head = head.next

	head.next = previous

def printList(head: Optional[ListNode]):

    while head :
        print(head, end =' ')
        head = head.next
        
    print()

if __name__ == '__main__':
    solution = Solution()
    res = nums2List([1,2,3,4])
    createCycle(res, 2)
    print(solution.detectCycle(res))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值