C 插入已排序的链表
尝试编写一个函数,要求用户输入一个整数,然后按升序将其插入链表C 插入已排序的链表,c,linked-list,C,Linked List,尝试编写一个函数,要求用户输入一个整数,然后按升序将其插入链表 typedef struct _listnode{ int item; struct _listnode *next; } ListNode; typedef struct _linkedlist{ int size; ListNode *head; } LinkedList; void insertSortedLinkedList(LinkedList *
typedef struct _listnode{
int item;
struct _listnode *next;
} ListNode;
typedef struct _linkedlist{
int size;
ListNode *head;
} LinkedList;
void insertSortedLinkedList(LinkedList *l)
{
ListNode *cur;
int x;
printf("please input an integer you want to add to the linked list:");
scanf("%d", &x);
if (l->head == NULL) // linkedlist is empty, inserting as first element
{
l->head = malloc(sizeof(ListNode));
l->head->item = x;
l->head->next = NULL;
}
else
{
cur = l->head;
if (x < cur->item) // data is smaller than first element, we will insert at first element and update head.
{
cur->next->item = cur->item; // store current element as next element.
cur->item = x;
cur->next = cur->next->next;
}
}
l->size++;
}
typedef结构\u列表节点{
国际项目;
结构_listnode*next;
}列表节点;
类型定义结构链接列表{
整数大小;
ListNode*头;
}链接列表;
void insertSortedLinkedList(LinkedList*l)
{
ListNode*cur;
int x;
printf(“请输入要添加到链接列表中的整数:”);
scanf(“%d”和&x);
如果(l->head==NULL)//linkedlist为空,则作为第一个元素插入
{
l->head=malloc(sizeof(ListNode));
l->head->item=x;
l->head->next=NULL;
}
其他的
{
cur=l->head;
如果(xitem)//数据小于第一个元素,我们将在第一个元素插入并更新head。
{
cur->next->item=cur->item;//将当前元素存储为下一个元素。
cur->item=x;
cur->next=cur->next->next;
}
}
l->size++;
}
函数尚未完成,但如果数据小于第一个元素,为什么我的代码不工作?插入函数的
else
分支假定cur->next
不是NULL
(因为您将值设置为cur->next->item
)。现在想象插入两个数字(第二个比第一个小)。在第一次插入中,l->head->next
设置为NULL
。因此,在第二次插入时,程序将在试图将cur->next->item
设置为某个值时崩溃。您应该创建一个节点(即,通过malloc()
)分配内存),根据需要初始化节点以包含字段,然后将其设置为cur->next
,首先需要为新元素创建节点,如下所示:
ListNode* newNode = malloc(sizeof(ListNode));
newNode ->item = x;
现在更改您的代码:
if (x < l->head->item) // data is smaller than first element, we will insert at first element and update head.
{
newNode->next = l->head;
l->head = newNode;
}
}
如果(xhead->item)//数据小于第一个元素,我们将在第一个元素插入并更新head。
{
新建节点->下一个=l->头部;
l->head=newNode;
}
}
正如您所说,代码不完整。是,通过列表循环,直到找到插入新节点的正确位置
可以编写1个代码来处理所有情况。
处理这些情况的一种常见方法是将节点放在链接列表的开头 请注意,以下划线开头的名称基本上是保留给“实现”使用的(它稍微有点细微差别,但只是稍微有点细微差别)。避免自己使用这样的名字。