Skip to content

Instantly share code, notes, and snippets.

@icameling
Last active July 18, 2022 08:04
Show Gist options
  • Save icameling/5e91ffdee980d5e7b1135331b5e46af2 to your computer and use it in GitHub Desktop.
Save icameling/5e91ffdee980d5e7b1135331b5e46af2 to your computer and use it in GitHub Desktop.
#链表 #反转链表
/**
* 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) {
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* post;
while (cur != NULL) {
post = cur->next; // save next node
cur->next = pre; // inverse list
pre = cur; // save the previous node
cur = post;
}
return pre;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment