xinyu04

导航

LeetCode 206 Reverse Linked List 翻转链表

Given the head of a singly linked list, reverse the list, and return the reversed list.

Solution

点击查看代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* nhead = nullptr, *cur = head, *tmp;
        while(cur){
            tmp = cur->next;
            cur->next = nhead;
            nhead = cur;
            cur = tmp;
        }
        return nhead;
    }
};

posted on 2022-07-24 16:19  Blackzxy  阅读(17)  评论(0编辑  收藏  举报