剑指Offer笔记2:06. 从尾到头打印链表 24. 反转链表

剑指 Offer 06. 从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        stack=[]
        while head:
            stack.append(head.val) #依次进栈
            head=head.next
        stack.reverse()            #利用reverse方法进行反转
        return stack





剑指 Offer 24. 反转链表 24. 反转链表

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur=head                #当前指针
        pre=None                #前指针
        while cur:              
            tmp=cur.next        #暂存当前指针的下一个节点
            cur.next=pre        #让当前指针的next指向pre所在节点,即反转
            pre=cur             #移动pre指针到当前cur指针所在位置
            cur=tmp             #当前指针cur移动到下一节点
        return pre

猜你喜欢

转载自blog.csdn.net/qq_56864896/article/details/130168326