Middle-题目77: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.
题目大意:
给出一个单链表和两个数m,n,翻转链表的m~n位。
题目分析:
还是用two pointers的思想,记住m的前驱,令其后继指向n,而n的后继指向m的next,以此类推。(在纸上画画,并多考虑一些特殊情况,如m是开头,n是结尾等)
源码:(language:c)

struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
     if (m == n || !head || !head->next)
         return head;
     int i = 1;
     struct ListNode* mPtr = head, *nPtr = head;
     for (struct ListNode* node = head; node; node = node->next, i++) {
         if (i == m)
             mPtr = node;
         if (i == n)
             nPtr = node;
     }
     if (mPtr == head) {
         while (mPtr != nPtr) {
             struct ListNode* temp = mPtr;
             mPtr = mPtr->next;
             temp->next = nPtr->next;
             nPtr->next = temp;
         }
         return nPtr;
     }
     else {
         struct ListNode* mPtrPrev = head;
         while (mPtrPrev->next != mPtr)
             mPtrPrev = mPtrPrev->next;
         mPtrPrev->next = nPtr;
         while (mPtr != nPtr) {
             struct ListNode* temp = mPtr;
             mPtr = mPtr->next;
             temp->next = nPtr->next;
             nPtr->next = temp;
         }
         return head;
     }
 }

成绩:
0ms,100%
Cmershen的碎碎念:
这道题在纯链表节点处理的题里面算是较难的了,须结合源码并在纸上演示一下才能理解指针间的关系。

你可能感兴趣的:(Middle-题目77:92. Reverse Linked List II)