试图编写一个函数,要求用户输入一个整数,然后按升序将其插入到链接列表中。插入已排序的链接列表
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++;
}
函数尚未完成,但为什么我的代码不工作,如果数据比第一个元素小?
请注意,以下划线开头的名字基本上是为'实现'使用的(它稍微比这更微妙,但只是稍微有点)。避免使用这些名字。 – 2015-04-05 05:47:25