Reverse a singly linked list.
源代码1:
/**
* 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) {
vector<int> v;
struct ListNode* tmp = head;
while(tmp != NULL ) {
v.push_back(tmp->val);
// struct ListNode* t = tmp->next;
tmp = tmp->next;
}
int len = v.size();
tmp = head;
for (int i = 0; i < len ;++i) {
tmp->val = v[len - i - 1];
tmp = tmp->next;
}
return head;
}
};
源代码2:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* tmp1 = head;
struct ListNode* tmp2;
struct ListNode* tmp3;
if (tmp1 != NULL) {
tmp2 = tmp1->next;
}
else return tmp1;
while(tmp2 != NULL) {
tmp3 = tmp2->next;
tmp2->next = tmp1;
tmp1 = tmp2;
tmp2 = tmp3;
}
head->next = NULL;
return tmp1;
}