# LeetCode: Reverse Linked List

43人阅读 评论(0)

Reverse a singly linked list.

/**
* 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;

}
};

/**
* 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;

}

1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：4653次
• 积分：823
• 等级：
• 排名：千里之外
• 原创：73篇
• 转载：8篇
• 译文：0篇
• 评论：0条