gpt4 book ai didi

c - 反转C中双链表的元素

转载 作者:行者123 更新时间:2023-12-02 05:17:57 26 4
gpt4 key购买 nike

这是我的做法——在链表的开头保留一个指针,在链表的末尾保留一个指针。向前推进头指针,向后推进尾指针,直到它们指向相同。在转发之前交换值。函数在调用时抛出段错误。为什么会这样?这是我的列表节点结构

struct dll
{
int number;
struct dll *next;
struct dll *prev;
};

这是我用来反转列表和主函数的函数

    int count=0;
void reverse(struct dll **root)
{
int temp;
struct dll *tail=NULL;
struct dll *temproot=NULL;
temproot =(*root);
for(;(temproot)->next !=NULL;(temproot)=(temproot)->next); //traversing to the end
tail= temproot;
while(((*root)->next != tail->prev) || ((*root)->next != tail))//one for even no. of nodes and one for odd no.of nodes
{
temp=(*root)->number; //swapping the numbers
(*root)->number=tail->number;
tail->number=temp;
(*root)=(*root)->next;
tail=tail->prev;
} //even after they are same, values need to be changed one last time
temp=(*root)->number;
(*root)->number=tail->number;
tail->number=temp;
(*root)=(*root)->next;
tail=tail->prev;
}
void insert(struct dll **root,int num)
{
struct dll *temp;
if(count==0)
{
if((*root)==NULL)
{
(*root)=(struct dll *)malloc(sizeof(struct dll));
(*root)->next=NULL;
(*root)->prev=NULL;
(*root)->number=num;
count++;
printf("\n%d",count);
}
}
else if((*root)->next==NULL)
{
temp=(struct dll *)malloc(sizeof(struct dll));
temp->next=NULL;
temp->prev=(*root);
temp->number=num;
(*root)->next=temp;
count++;
printf("\n%d",count);
}
else
{
insert(&(*root)->next,num);
}

}
main()
{
struct dll *head=NULL;
int i,n,num;
while(1)
{
printf("Enter 1 for insert, 3 for reverse, 0 for exit\n");
scanf("%d",&n);
switch(n)
{
case 1:printf("Enter number\n");
scanf("%d",&num);
insert(&head,num);
break;
case 3:reverse(&head);break;
case 0:exit(0);
default:printf("Enter correct value\n");
}
}

}

最佳答案

通过颠倒列表的顺序,您的意思是交换所有项目的 next 和 prev 指针吗?这段未经检查的代码可能会起到作用:

void reverse(struct dll **root)
{
struct dll *buff=NULL;
struct dll *start=*root;

unsigned char stop=0;
while(stop==0){
if(*root==NULL){
stop=1;
break;
}
buff=(*root)->prev;
(*root)->prev=(*root)->next;
(*root)->next=buff;

*root=(*root)->prev;//the next to treat is the previous one now
if(*root==start){
//this test handle the case of "looping" double linked list
stop=1;
break;
}
}
}

此代码假定 *root 是列表的开头。最后,*root 仍然是列表的开头。

再见,

弗朗西斯

关于c - 反转C中双链表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20299700/

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