leetcode-206-Reverse Linked List

来源:互联网 发布:mmd怎么自己做动作数据 编辑:程序博客网 时间:2024/04/27 17:00

问题

题目:[leetcode-206]

思路

递归的时候注意:

  • 头结点的保存时机(边界条件时做的)
  • 每次head->next = NULL;不要忘了修改

代码(递归)

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

思路1

当然,头插法也可以。没必要节点复制,直接改指针也可以。当然,这个角度说也有点像就地置逆。

代码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) return NULL;        ListNode* ret = NULL;        while(head){            ListNode* nex = head->next;            if(!ret)             {                ret = head;                ret->next = NULL;            }            else            {                head->next = ret;                ret = head;            }            head = nex;        }        return ret;    }};

思路2

就地置逆。

代码2(就地置逆)

/** * 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)            return NULL;        ListNode* ret = NULL;        while(head)        {            ListNode* nex = head->next;            head->next = ret;            ret = head;            head = nex;        }        return ret;    }};
0 0
原创粉丝点击