Skip to content

Latest commit

 

History

History
executable file
·
69 lines (60 loc) · 2.74 KB

206. Reverse Linked List.md

File metadata and controls

executable file
·
69 lines (60 loc) · 2.74 KB

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 ##(一)题目

Reverse a singly 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) {
        ListNode* p = head;
        ListNode* pre = NULL;//记录上一个节点
        while(p!=NULL){
            ListNode* temp = p->next;//暂存p的下一个节点
            p->next = pre;//反转,p的next指向pre
            pre = p;
            p=temp;
        }
        return pre;
    }
};

递归版本:

/**
 * 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) {
        return recurReverseList(head,NULL);
    }
    ListNode* recurReverseList(ListNode* cur,ListNode* pre){
        if(cur==NULL) return pre;
        ListNode* temp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = temp;
        return recurReverseList(cur,pre);
    }
};