一、问题描述
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
二、代码实现
/**
* 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) {
//pre永远指向null,相当于一个尾节点
ListNode* pre = NULL;
ListNode* cur = head;
while(cur != NULL){
//next用来保存下一个节点。因为会把当前节点cur拿下来,赋值给pre
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};