該函數將要求用戶輸入一個整數,然後按升序將其插入到鏈表中。如果當前值已經存在,將不會插入。按升序將值插入排序後的鏈表
typedef struct _listnode{
int item;
struct _listnode *next;
} ListNode;
typedef struct _linkedlist{
int size;
ListNode *head;
} LinkedList;
void insertSortedLinkedList(LinkedList *l)
{
ListNode *cur = l->head;
ListNode* newNode = malloc(sizeof(ListNode)); // create the node to be inserted
int x;
printf("please input an integer you want to add to the linked list:");
scanf("%d", &x);
newNode->item = x;
newNode->next = NULL;
if (l->head == NULL) // linkedlist is empty, inserting as first element
{
l->head = malloc(sizeof(ListNode));
l->head->item = x;
l->head->next = NULL;
l->size++;
}
else
{
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;
l->size++;
return;
}
while (cur->next != NULL) // loop through the linkedlist
{
if (cur->next->item > x) // next element is bigger than data, we will insert it now.
{
if (cur->item != x) // if current element is not same as data, it must not have already existed.
{
newNode->next = cur->next;
cur->next = newNode;
l->size++;
return;
}
}
if (cur->next == NULL) // we have reached the last element and data is even greater than that. we will then insert it as last element.
{
cur->next = newNode;
l->size++;
return;
}
cur = cur->next;
}
}
}
不知何故,它有一個錯誤。當我嘗試插入以下內容時,我得到了這些結果。如果數據大於存在的數據,它也不會插入。
Insert : 10
Result : 10
Insert : 5
Result : 5 10
Insert : 8
Result : 5 8 10
Insert : 10
Result : 5 8 10
Insert : 7
Result : 5 7 8 10
Insert : 9
Result : 5 7 8 9 10
Insert : 6
Result : 5 6 7 8 9 10
Insert : 5
Result : 5 6 5 7 8 9 10 << why?
你是怎麼發現當你調試? – 2015-04-05 07:24:29
問題出在'if(cur-> item!= x)'。當你在節點'6'上時,它檢查'7'是否大於'5'。是的,然後它檢查是否'5!= 6' ..真..所以它將它插入那裏 – user7 2015-04-05 07:27:22
@ user7我不明白當前節點如果我的列表已經有5 6 7 8 9 10,我想插入5.它會檢測到節點6(cur-> next)大於5,然後檢查是否5!= 5,因此退出函數 – 2015-04-05 07:39:36