Lost Monkey

我是一只迷失的程序猿

LeetCode: Reverse Linked List

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;
    
    
    
}



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012309913/article/details/52368652
个人分类: LeetCode
上一篇LeetCode: Wiggle Sort II
下一篇LeetCode: Merge Two Sorted Lists
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭