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

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

解析:链表翻转,采用循环和递归的方式。

解法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) {
        if(head == NULL || head->next == NULL)
            return head;
        ListNode* pre = NULL, *next = NULL;
        while(head)
        {
            next=head->next;
            head->next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
};

解法2:递归方式

如果head不为空,则将head->next传入下一次递归,new_list表示head->next进入递归返回的元素,一直找到最后一个元素,此时new_list指向最后一个元素,然后把head下一个节点的next指向head,相当于把head指向了末尾,同时把head->next端口,一直回溯回去。

/**
 * 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 == NULL || head->next == NULL)
            return head;
        ListNode* new_list = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return new_list;
    }
};

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据