程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Reverse Linked List II

Reverse Linked List II

編輯:C++入門知識

題目:


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 < = m < = n < = length of list.

代碼如下:

ListNode *reverseBetween(ListNode *head, int m, int n) {
        if(m==n)return head;
        int i=1;
        if(m==1)
        {
            ListNode *head1=head;
            while(i<n)
            {
                ListNode *tmp=head1->next;
                head1->next=tmp->next;
                tmp->next=head;
                head=tmp;
                i++;
            }
        }
        else
        {
            ListNode *head1=head;
            while(i<m-1)
            {
                head1=head1->next;
                i++;
            }
            ListNode *head2=head1->next;
            while(i<n-1)
            {
                ListNode *tmp=head2->next;
                head2->next=tmp->next;
                tmp->next=head1->next;
                head1->next=tmp;
                i++;
            }
        }
        return head;
    }


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved