当前位置: 代码迷 >> 综合 >> 每K个节点一组翻转链表 Leetcode 25 Python
  详细解决方案

每K个节点一组翻转链表 Leetcode 25 Python

热度:80   发布时间:2024-01-31 10:22:35.0

利用栈结构

首先能想到的当然是通过栈的结构,来进行反转,设置一个栈,先进后出的性质。唯一需要注意的当剩余的元素不足以放到栈里面的时候,就停止反转就好来。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution(object):def reverseKGroup(self, head, k):""":type head: ListNode:type k: int:rtype: ListNode"""#用于链接头元素Phead = ListNode(None)p = Pheadwhile True:count = kstack = []tmp = headwhile count and tmp:stack.append(tmp)tmp = tmp.nextcount -= 1#跳出上面循环的时候,tmp是第k+1的元素来#如果上面循环结束的时候,count还不为0,那就代表不足k个元素if count :p.next = headbreak#对k个元素进行反转while stack:p.next = stack.pop()p = p.next#与剩下链表链接起来p.next = tmphead = tmpreturn Phead.next

尾插法

思路就是用一个指针指向头节点,一个指向尾部节点,让头节点连接尾部节点所连接的节点。然后让之前头部节点连接的节点,连接头部节点,一直到第一个节点为尾部节点。
eg,1,2,3,4,5,k=3,之前1连接的是2,现在让1,连接4,2之前连接的3,然后让他连接1,3之前连接4,现在连接2,然后让3成为头节点,从4开始往后继续。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution(object):def reverseKGroup(self, head, k):""":type head: ListNode:type k: int:rtype: ListNode"""Phead = ListNode(None)Phead.next, pre ,tail = head, Phead, Pheadwhile True:count = kwhile count and tail:count -= 1tail = tail.nextif not tail:breakhead = pre.nextwhile pre.next!= tail:#得到下一个元素cur = pre.next# pre与cur.next 连接起来,画图可以看出来#cur是新的链表的第一个节点pre.next = cur.nextcur.next = tail.next#每次第一个节点都要知道插谁后面,这一句就是为了更新tail.next = cur#当前面都已经反转完毕,就要进行要一个k组的转换,需要更新,pre和tail#按照k=3的例子,此时pre和tail就指向1这个节点,而我们第一步创建的pre和tail#指向的是我们自己建立的节点#感受一下建立一个新的头节点的好处pre = headtail= headreturn Phead.next

递归法

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution(object):def reverseKGroup(self, head, k):""":type head: ListNode:type k: int:rtype: ListNode"""cur = headcount = 0while cur and count != k:cur = cur.nextcount += 1#通过设置cur,把原先的链表切成几段,每一段在一个递归体里面进行处理。if count == k:cur = self.reverseKGroup(cur,k)while count:tmp = head.nexthead.next = curcur = headhead = tmpcount -= 1head = curreturn head


  相关解决方案