0
因此,我試圖找到具有最小值的節點,並將其放在列表的末尾。我有兩個功能試圖找出實現它的多種方式。但列表打印出來不變。LinkedList錯誤?在C
任何幫助,將不勝感激。
我的代碼:
#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;
}
't-> next = malloc(sizeof(* t));':'next'最後一個元素必須是'NULL' 。 – BLUEPIXY