gpt4 book ai didi

C++程序将链表从位置m反转到n

转载 作者:行者123 更新时间:2023-11-30 03:41:32 25 4
gpt4 key购买 nike

我在这个简单的问题上停留了几个小时...有人可以帮忙...我哪里错了吗?

问题:将链表从位置 m 反转到 n。就地一次性完成。

例如:给定 1->2->3->4->5->NULL,m = 2 和 n = 4,

返回 1->4->3->2->5->NULL。

注意:1≤m≤n≤列表长度

#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;
}

我得到的输出与我的输入相同!!....陷阱在哪里?

最佳答案

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

修改为

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

关于C++程序将链表从位置m反转到n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37360699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com