Reverse Linked List 2

来源:互联网 发布:淘宝必须用支付宝吗 编辑:程序博客网 时间:2024/06/05 16:16

1.dummy Node 的使用

感觉不是简单的就是 new一个dummy node 然后 dummy->next = head; 就好了, 这样是虚的

最关键的是 dummy->next = head; 之后 head 要再从dummy 开始 head = dummy; 这样的dummy才是有效的 并且连续的 ,at this point which should starts from dummy. otherwise this dummy is not consistent.


2. reverse linked list 2 其实和1 很像 核心部分很像 但是也是有诀窍的 比如

a. 四个点 prevM, M,N,postN. 在核心变换的时候 其实是在用N 和postN 进行的,然后最后再把preM 与nNode 和 M 与postN连接上

b. 考虑特殊情况 0或者1 的时候不用转化

c. 还有一个就是每一个循环的时候边界条件一定要特别注意 it is smaller or smaller and equal 

class Solution {public:    ListNode* reverseBetween(ListNode* head, int m, int n) {        if ((head == NULL) || (head->next == NULL))        {            return head;        }        int counter = 1;        ListNode *dummyNode = new ListNode(0);        dummyNode->next = head;        head = dummyNode;        while (counter < m)        {            head = head->next;            ++counter;        }        ListNode *prev  = head;        ListNode *mNode = head->next;        ListNode *post  = mNode->next;        ListNode *nNode = head->next;        ListNode *temp = new ListNode(0);        for (int i = m; i < n; ++i)        {            temp = post->next;            post->next = nNode;            nNode = post;            post = temp;        }        prev->next = nNode;        mNode->next = post;        return dummyNode->next;                    }


The other solution which is using the dummy node too.

class Solution {public:    ListNode* reverseBetween(ListNode* head, int m, int n) {        if ((head == NULL) || (head->next == NULL))        {            return head;        }        int counter = 1;        ListNode *dummyNode = new ListNode(0);        dummyNode->next = head;        ListNode *prev  = dummyNode;        while (counter < m)        {            prev = prev->next;            ++counter;        }        ListNode *mNode = prev->next;        ListNode *post  = mNode->next;        ListNode *nNode = prev->next;        ListNode *temp = new ListNode(0);        for (int i = m; i < n; ++i)        {            temp = post->next;            post->next = nNode;            nNode = post;            post = temp;        }        prev->next = nNode;        mNode->next = post;        return dummyNode->next;                    }};


还有一个reverse linked list 的 recursive 的方法 但是真的有必要吗 到时候再写吧

0 0
原创粉丝点击