问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
#include<stdio.h>
#include<stdlib.h>
#define Type int
struct list{
Type data;
struct list * nextptr;
};
typedef struct list LIST;
typedef LIST * LISTPTR;
LIST * createlist(LISTPTR headptr);
void FindAndSwap(LISTPTR currentptr);
void printlist(LISTPTR currentptr);
void freelist(LISTPTR headptr);
int main(void)
{
int ss1,ss2,tt1,tt2;
LISTPTR headptr=NULL;
headptr=createlist(headptr);
FindAndSwap(headptr);
printlist(headptr);
freelist(headptr);
return 0;
}
LIST * createlist(LISTPTR headptr)
{
LISTPTR currentptr,newptr;
int num;
newptr=malloc(sizeof(LISTPTR));
newptr->nextptr=NULL;
headptr=newptr;
scanf("%d",&num);
while(num!=-1){
newptr=malloc(sizeof(LIST));
newptr->data=num;
newptr->nextptr=NULL;
if(headptr->nextptr==NULL){
currentptr=newptr;
headptr->nextptr=currentptr;
}
else{
currentptr->nextptr=newptr;
currentptr=newptr;
}
scanf("%d",&num);
}
return headptr;
}
void FindAndSwap(LISTPTR currentptr)
{
int a,s1,s2,t1,t2;
scanf("%d %d %d %d",&s1,&t1,&s2,&t2);
a=0;
LISTPTR preptr1,preptr2,tptr1,tptr2,tptr3,tptr4,afterptr1,afterptr2;
currentptr=currentptr->nextptr;
while(currentptr!=NULL){
a+=1;
if(a==s1){
tptr1=currentptr;
preptr1->nextptr=currentptr;
}
if(a==t1){
tptr2=currentptr;
afterptr1=tptr2->nextptr;
}
if(a==s2){
tptr3=currentptr;
preptr2->nextptr=currentptr;
}
if(a==t2){
tptr4=currentptr;
afterptr2=tptr4->nextptr;
}
currentptr=currentptr->nextptr;
}
if(t1!=s2-1){
tptr2->nextptr=afterptr2;
preptr2->nextptr=tptr1;
tptr4->nextptr=afterptr1;
preptr1->nextptr=tptr2;
}
else if(t1==s2-1){
tptr2->nextptr=afterptr2;
tptr4->nextptr=tptr1;
preptr1->nextptr=tptr3;
}
}
void printlist(LISTPTR currentptr)
{
currentptr=currentptr->nextptr;
printf("The new list is:");
while(currentptr!=NULL){
if(currentptr->nextptr!=NULL){
printf("%d ",currentptr->data);
}
else if(currentptr->nextptr==NULL){
printf("%d\n",currentptr->data);
}
currentptr=currentptr->nextptr;
}
}
void freelist(LISTPTR headptr)
{
LISTPTR temptr;
while(headptr!=NULL){
temptr=headptr;
headptr=headptr->nextptr;
free(temptr);
}
}
运行结果及报错内容
输入数据后运行不出来,我认为是那个FindAndSort函数有问题
我的解答思路和尝试过的方法
我想要达到的结果输入:1 2 3 4 5 6 7 8 9 10 -1
1 1 4 7
输出:The new list is:4 5 6 7 2 3 1 8 9 10