試圖編寫一個函數,要求用戶輸入一個整數,然後按升序將其插入到鏈接列表中。插入已排序的鏈接列表
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