链表2

1、反转链表

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

2、解答: 我当时总是在想 用两个指针行不行,然后一致纠结,然后用一个临时变量存储的化,很快就可以解出来。改变指针的指向,但是也要保存指针。


3、C++代码

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
       ListNode *prev = nullptr;               //这一步很重要
       ListNode *curr = head;
        while(curr != nullptr){
            ListNode *temp = curr->next;         //保存当前节点的下一个指针位置
            curr->next = prev;
            prev = curr;
            curr = temp;
            
        }
        return prev;         //返回头指针
       
        
    }
};


 python代码

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev_node = None
        curr_node = head
        while curr_node:
            temp_node = curr_node.next
            curr_node.next = prev_node
            prev_node = curr_node
            curr_node = temp_node
            
        
        head = prev_node
        return head

猜你喜欢

转载自blog.csdn.net/qq_31307013/article/details/80191613