LeetCode 206: 反转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

C++代码如下:(用递归的方式)

/**
 * 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* rHead = reverseList(head->next); // 反转得到新链表的头节点
        head->next->next = head; // 当前节点的下一个节点的next指针反转过来
        head->next = NULL; // 设置新链表的尾节点
        return rHead;
    }
};

非递归的方式:

/**
 * 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 *temNode=new ListNode(0); //用于保存的中间变量
        ListNode* tail=head->next; //反转前的尾节点,反转后的头节点
        head->next=NULL;
        while(tail->next != NULL)
        {
            temNode->next=tail->next;
            tail->next=head;
            head=tail;
            tail=temNode->next;
        }
        tail->next=head;
        delete temNode;
        return tail;
     
    }
};

注意:在刷leetcode时通过后注意关注事件,多看参考代码,看能否优化。有时候想法是一样的,但写法不一样就会总成事件有差异。

猜你喜欢

转载自blog.csdn.net/annabelle1130/article/details/88242451