[Leetcode] Reverse Linked List

Reverse Linked List 题解

题目来源:https://leetcode.com/problems/reverse-linked-list/description/


Description

Reverse a singly linked list.

Solution


class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head -> next == NULL)
            return head;
        ListNode *preNode = head,
                 *curNode = preNode -> next,
                 *nextNode = curNode -> next;
        while (true) {
            curNode -> next = preNode;
            if (nextNode == NULL)
                break;
            preNode = curNode;
            curNode = nextNode;
            nextNode = nextNode -> next;
        }
        head -> next = NULL;
        return curNode;
    }
};


解题描述

这道题是经典的链表反转。使用的解法是使用preNodecurNodenextNode三个相邻的指针,每次将curNode指向preNode,然后三个指针都向后移,最后将head的下一节点置空即可。

posted @ 2018-01-29 13:09  言何午  阅读(140)  评论(0编辑  收藏  举报