Leetcode 206. Reverse Linked List反转链表

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

题目链接:https://leetcode.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) {
        vector<int> tmp;
        ListNode *thead=head;
        while(thead)
        {
            tmp.emplace_back(thead->val);
            thead=thead->next;
        }
        thead=head;
        for(int i=tmp.size()-1;i>=0;i--)
        {
            thead->val=tmp[i];
            thead=thead->next;
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/88574981