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->NULLm = 2 and n = 4,

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

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

思路:控制好链表的哨兵节点和尾部节点,要控制好使用到的每个节点的位置

java代码:

  1. public ListNode reverseBetween(ListNode head, int m, int n) {
  2. if(head==null || head.next==null) return head;
  3. if(m==n) return head;
  4. ListNode dummy = new ListNode(-1);
  5. dummy.next = head;
  6. ListNode pre = dummy;
  7. ListNode p = head;
  8. int i=1;
  9. for(i=1;i<m;i++) {
  10. pre = p;
  11. p = p.next;
  12. }
  13. ListNode start = p;
  14. while(i<n) {
  15. p = p.next;  //p进入时为即将遍历到的上一个节点
  16. start.next = p.next;
  17. p.next = pre.next;
  18. pre.next = p;
  19. p = start;
  20. i++;
  21. }
  22. return dummy.next;
  23. }

C++代码:

  1. ListNode *reverseBetween(ListNode *head, int m, int n) {
  2. if(head==NULL || head->next==NULL) return head;
  3. if(m==n) return head;
  4. ListNode *dummy = new ListNode(0);
  5. dummy->next=head;
  6. ListNode *p=dummy;
  7. int i=0;
  8. for(i=1;i<m;i++) p=p->next;
  9. head=p->next; //head为每次要遍历到的节点
  10. i=i+1;
  11. while(i<=n) {
  12. ListNode *q=head->next;  
  13. head->next=q->next;
  14. q->next=p->next;
  15. p->next=q;
  16. i++;
  17. }
  18. return dummy->next;
  19. }
posted @ 2014-07-31 22:57  purejade  阅读(74)  评论(0编辑  收藏  举报