2016-05-21 5 views
1

私はこの簡単な質問に何時間も立ち往生しています...誰かが助けてくれるのですか...どこが間違っていますか?リンクリストを位置mからnに戻すためのC++プログラム

質問:リンクされたリストを位置mからnに反転します。それをインプレースとワンパスで行います。例えば

: 考える1-> 2-> 3-> 4-> 5-> NULL、M = 2、N = 4、

リターン1-> 4-> 3-> 2- > 5-> NULL。

注:リスト

#include<stdio.h> 
#include<bits/stdc++.h> 
using namespace std; 

struct node 
{ 
    int data; 
    struct node *next; 
}; 
typedef struct node ListNode; 

node *newNode(int key) 
{ 
    node *temp = new node; 
    temp->data = key; 
    temp->next = NULL; 
    return temp; 
} 

ListNode* reverseUpto(ListNode *head, int size) 
{ 
    if(size<=1) 
     return head; 
    ListNode *cur=head,*newhead=NULL,*temp; 
    for(int i=0;i<size;i++) 
    { 
     temp=cur; 
     cur=cur->next; 
     temp->next=newhead; 
     newhead=temp; 
    } 
    head->next=cur; 
    return newhead; 
} 

ListNode* reverseBetween(ListNode* A, int m, int n) 
{ 
    ListNode *head=A; 
    if(m==n) 
     return A; 
    ListNode *dummyhead=newNode(0); 
    dummyhead->next=head; 
    ListNode *prev=dummyhead; 
    ListNode *cur=head; 
    int counter=1; 
    while(counter<m) 
    { 
     printf("counter= %d  prev=%d  cur=%d\n",counter,prev->data,cur->data); 
     counter++; 
     prev=cur; 
     cur=cur->next; 
    } 
    prev->next=NULL; 
    ListNode * retPtr=reverseUpto(cur,m-n+1); 
    prev->next=retPtr; 
    return A; 
} 

void printlist(node *head) 
{ 
    while(head != NULL) 
    { 
     cout << head->data << " "; 
     head = head->next; 
    } 
    cout << endl; 
} 

int main() 
{ 
    node *head1 = newNode(1); 
    head1->next = newNode(2); 
    head1->next->next = newNode(3); 
    head1->next->next->next = newNode(4); 
    head1->next->next->next->next = newNode(5); 
    head1->next->next->next->next->next = newNode(6); 
    head1->next->next->next->next->next->next = newNode(7); 
    head1->next->next->next->next->next->next->next = newNode(8); 
    cout << "Given linked list\n"; 
    printlist(head1); 
    head1=reverseBetween(head1,3,5); 
    cout << "\nReversed linked list\n"; 
    printlist(head1); 
    return 0; 
} 

私は私の入力!!と同じ出力を取得していますの1≤M≤n個の≤長....落とし穴がありますか?

+4

http://codereview.stackexchange.com/questions/106811/reverse-part-of-a-linked-list – Idos

+0

に変更読んでください:[質問] –

+0

私の質問はどこに私のソリューションの落とし穴ですか?私は自分の入力と同じ出力を得ています! –

答えて

2
ListNode * retPtr=reverseUpto(cur,m-n+1); 

あなたの具体的な質問は何ですか?

ListNode * retPtr=reverseUpto(cur,n-m+1); 
+0

ああ...私の悪い! ....ありがとう...それは犯人だった! –

関連する問題