Define a function, input the head node of a linked list, reverse the linked list and output the head node of the reversed linked list.
Example:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
limit:
0 <= number of nodes <= 5000
Note: This question is the same as question 206 on the main site: https://leetcode-cn.com/problems/reverse-linked-list/
Problem-solving ideas:
Reference: https://blog.csdn.net/qq_30457077/article/details/114111054
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;//前一个节点
ListNode* curr = head;//当前节点
while (curr) {
ListNode* next = curr->next;//获取当前节点的下一个节点
curr->next = prev;//当前节点指向前一个节点:反转方向
prev = curr;//当前节点赋值给前一个节点
curr = next;//下一个节点赋值给当前节点
}
return prev;//此时为新的头节点
}
};