反转链表
思路:双指针
class Solution:
def ReverseList(self, pHead):
pre=None #pre指针记录当前结点点的前一个结点
cur=pHead
while cur:
tmp=cur.next
cur.next=pre #当前结点的next指针改为指向前一个结点进行反转
pre=cur #pre和cur指针向前移动
cur=tmp
return pre
链表中的节点每k个一组反转
思路:递归
class Solution:
def reverseKGroup(self , head , k ):
def reverseingroup(head,tail):#组内反转,(head,tail)左闭右开
pre=None
cur=head
while cur != tail:
tmp=cur.next
cur.next=pre
pre=cur
cur=tmp
return pre
#1.首先判断该组是否需要反转:个数小于k不需要反转
tail=head
for i in range(k):
if tail is None:
return head
else:
tail=tail.next
#最后得到的tail是该组尾结点的下一个结点=下一组的头结点
#2.组内反转,返回的头结点记为newhead
newhead=reverseingroup(head,tail)
#3.每次递归后连接两组:当前组的head成为尾结点,指向下一组的返回的头结点。
head.next=self.reverseKGroup(tail,k) #下一组从tail开始
return newhead
从尾到头打印链表
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
stack=[]
while listNode:#从头到尾遍历,逆序输出
stack.append(listNode.val)
listNode=listNode.next
return stack[::-1]