Reverse a singly linked list.
定义3个相邻的指针,pre、cur、post,,每次往后挪一位,将cur的next指向pre,直到post为空。
/** * 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) {if(head == NULL || head->next == NULL)return head;ListNode* pre = head;ListNode* cur = pre->next;ListNode* post = cur->next;pre->next = NULL;while(post){cur->next = pre;pre = cur;cur = post;post = post->next;}cur->next = pre;return cur;}};
版权声明:本文为博主原创文章,未经博主允许不得转载。
也不要说曾经失去,失去的不是永远失去,得到的不是永远拥有,