我正在尝试编写单向链表的基于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