LeetCode | 92. Reverse Linked List II


题目:

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤ length of list.


题意:

输入一个单项链表,以及位置索引m和n,要求将链表中第m到第n个元素的链表段进行翻转,然后输出。例子如上所述。难点是输入的m和n有可能是边界索引,需要特殊处理。


解题思路:

首先从头至尾扫描链表,符合[m, n]索引区间的链表节点压入栈s,并保存m-1和n+1个节点的指针地址。将[m, n]链表段进行翻转,然后将m-1个指针和n+1个指针重新接入即可。需要注意的就是m和n包含链表边界第1个和最后一个节点时的处理。


代码:

ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(head == NULL || head->next == NULL)
            return head;
        stack<ListNode*> s;
        ListNode *p, *q, *r, *start = NULL, *tail = NULL, *h = NULL;
        int length = 0;
        for(p = head; p != NULL; p = p->next, length++)
        {
            if(length >= m - 1 && length <= n - 1)
                s.push(p);
            else if(length == m - 2)
                start = p;
            else if(length == n)
                tail = p;
        }
        if(start == NULL)
            head = s.top();
        while(!s.empty())
        {
            p = s.top();
            s.pop();
            if(h == NULL)
            {
                h = p;
                q = h;
            }
            else
            {
                q->next = p;
                q = p;
            }
        }
        q->next = tail;
        if(start != NULL)
            start->next = h;
        return head;
    }

链表的操作大多需要注意的是头尾节点的处理,中间部分需要注意连接关系即可。






猜你喜欢

转载自blog.csdn.net/iLOVEJohnny/article/details/79701063