我正在嘗試編寫單向鏈表的基於C的實現。單鏈表實現問題
#include<stdio.h>
struct sllist {
int data;
struct sllist *next;
};
void InsertInLinkedList(struct sllist *head, int data, int position);
int main()
{
int x;
struct sllist *s=NULL;
InsertInLinkedList(s,5,1);
x=ListLength(s);
printf("%d\n",x);
return 0;
}
int ListLength(struct sllist *head)
{
struct sllist *current = head;
int count = 0;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
void InsertInLinkedList(struct sllist *head, int data, int position)
{
int k = 1;
struct sllist *p, *q, *newNode;
newNode = (struct sllist *)malloc(sizeof(struct sllist));
if (!newNode) {
printf("Memory Error\n");
return;
}
newNode->data = data;
p = head;
if (position == 1) {
newNode->next = NULL;
head = newNode;
} else {
while ((p != NULL) && (k < position - 1)) {
k++;
q = p;
p = p->next;
}
if (p == NULL) {
q->next = newNode;
newNode->next = NULL;
} else {
q->next = newNode;
newNode->next = p;
}
}
}
我嘗試添加一個節點到列表中,然後驗證長度。但是,我得到的結果是0而不是1。我犯了什麼錯誤?
感謝
只是一個fyi,任何時候你在位置1插入,你將失去整個鏈表。 – Joel