lc 反转链表

链接:https://leetcode-cn.com/problems/reverse-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) {
        if(head == nullptr) return nullptr;
        ListNode* cur = head;
        ListNode* ret = nullptr;
        while(cur) {
            if(ret == nullptr) {
                ListNode* temp = new ListNode(cur->val);
                ret = temp;
                cout << cur->val << endl;
            }
            else {
                ListNode* temp = new ListNode(cur->val);
                temp->next = ret;
                ret = temp;
                cout << cur->val << endl;
            }
            cur = cur->next;
        }
        return ret;
    }
};
View Code

思路:头插。

posted on 2020-05-24 23:22  FriskyPuppy  阅读(113)  评论(0编辑  收藏  举报

导航