gpt4 book ai didi

c - 链表错误?在C中

转载 作者:行者123 更新时间:2023-11-30 17:04:33 26 4
gpt4 key购买 nike

所以我试图找到值(value)最小的节点并将其放在列表的末尾。我有两个函数试图找出实现它的多种方法。但列表打印出来没有变化。

任何帮助将不胜感激。

我的代码:

    #include <stdio.h>
#include <stdlib.h>

typedef struct node * linkk;
typedef struct struct_list * list;

struct node {
int item;
linkk next;
};

int ConnectSmallElementToLast(linkk A);
int Connect(linkk A);


int main(int argc, const char * argv[]) {

linkk t = malloc(sizeof(*t));
linkk head = t;


for (int i = 0; i < 10; i++)
{
t->item = i;
t->next = malloc(sizeof(*t));
t = t->next;
}

connect(t);

for ( int i = 0; i <10; i++)
{
printf("%d\n",head->item);
head = head->next;
}





return 0;
}

int ConnectSmallElementToLast( linkk A)
{
linkk L = A;
linkk head = A;
linkk printhead = L;
linkk smallestNode = NULL;
linkk pre = NULL;
linkk post = NULL;
int count=1, Number;
Number = L->item;
L = L->next;
for (int i = 1; i < sizeof(L);i++)
{
if(Number > L->item)
{
Number == L->item;
smallestNode = L;
post = L->next;
L = L->next;
count++;
}
else{L = L->next;}
}
L->next = smallestNode;
for (int i = 0; i< sizeof(head);i++)
{
if ( i == (count-1))
{
head->next = post;
}else if( head->next == NULL)
{
head->next = smallestNode;
}
}
for (int i = 0; i<sizeof(printhead);i++)
{
printf("%d\n",printhead->item);
printhead = printhead->next;
}

return 0;
}

int Connect(linkk A)
{
linkk L = A;
linkk pre = NULL;
linkk post = NULL;
linkk current = NULL;
linkk head = L;
int smallest;
int NumberPre,NumberCur,NumberPost;
while (L != NULL && L->next !=NULL && L!=NULL)
{
pre = L;
current = L->next;
post = L->next->next;
NumberPre = pre->item;
NumberCur = L->next->item;
NumberPost = L->next->next->item;
if ( NumberCur < NumberPre && NumberCur < NumberPost )
{
pre->next = post;
smallest = NumberCur;

}else if(NumberPre < NumberCur && NumberPre < NumberPost)
{
L = current;
smallest = NumberPre;
}
pre = pre->next;
current = current->next;
post = post->next;

}
for ( int i = 0; i<sizeof(head);i++)
{
if (head->next == NULL)
{
head->next->item = smallest;
head->next->next = NULL;
}
}
return 0;
}

最佳答案

首先,你的代码实现链表的方式很奇怪。尝试用谷歌搜索其他人如何使用链接列表。

从您的代码中:

linkk t = malloc(sizeof(*t));
linkk head = t;


for (int i = 0; i < 10; i++)
{
t->item = i;
t->next = malloc(sizeof(*t));
t = t->next;
}

它创建一个链表,其中包含头和 10 个节点。

在您的连接方法中:

for ( int i = 0; i<sizeof(head);i++)
{
if (head->next == NULL)
{
head->next->item = smallest;
head->next->next = NULL;
}
}

sizeof(head) 是 sizeof(linkk),它是指向节点的指针。好吧,在 32 位系统中它始终是 4 个字节。

这解释了循环失败的原因。

此外,在分配给列表之前,您需要为节点分配内存。就像您在 main() 的 for 循环中所做的那样。

还有一件事,人们通常使用“create”函数来包装创建节点时需要做的所有事情。

例如。1.分配内存2.赋值3.将其放入列表

关于c - 链表错误?在C中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35714367/

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