4.4 反转链表

题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

提示:

链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000

来源:力扣(LeetCode)
链接: link.

思路

  1. 定义 cur 指向首节点, pre 是它的前节点, temp是它的后节点
  2. while ( cur ) :
    记下 cur 的后节点
    让cur 指向前节点
    cur,pre 往后挪
    3.返值

具体代码实现(C++)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    	//1
        ListNode* temp;
        ListNode* cur = head;
        ListNode* pre = nullptr;
        //2
        while (cur) {
            temp = cur->next; //记下 cur 的后节点
            cur->next = pre; //cur 指向前节点 
			//cur,pre 往后挪
            pre = cur; 
            cur = temp;  
        }  
        //3 
        return pre;     
    }
};

模型(知识点)

1.反转链表

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    	//1
        ListNode* temp;
        ListNode* cur = head;
        ListNode* pre = nullptr;
        //2
        while (cur) {
            temp = cur->next; //记下 cur 的后节点
            cur->next = pre; //cur 指向前节点 
			//cur,pre 往后挪
            pre = cur; 
            cur = temp;  
        }  
        //3 
        return pre;     
    }
};

版权声明:本文为qq_51047851原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。