2013-12-18 61 views
0

我正在尝试编写单向链表的基于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。我犯了什么错误?

感谢

+0

只是一个fyi,任何时候你在位置1插入,你将失去整个链表。 – Joel

回答

2

此代码:

if (position == 1) { 
    newNode->next = NULL; 
    head = newNode; 
} 

没有效果......因为newNode保持超脱,头迷路。

在链表中插入节点的函数应返回修改后的列表,或接受指向指针的指针。像下面这样:

void InsertHead(struct sllist **list, struct sllist *new_node) { 
    new_node->next = *list; 
    *list = new_node; 
} 
1

为了进一步解释马努 - fatto的意见,即“头迷路” - 当你传递一个指针的函数,你只有经过了许多的副本。修改函数内部的数字只会修改函数的本地副本。它对调用函数的指针没有影响。

+0

感谢您的解释。我在理解实现时遇到了一些问题。当将一个节点添加到列表的末尾时,它会执行q-> next = newNode;不应该是p-> next = newNode,因为p是最后一个节点的下一个指针? –

+0

有两个地方代码“q-> next = newNode”发生......在第一种情况下,p是NULL,所以你绝对不想做p->任何事情。在第二种情况下,p指向插入节点之后的节点。这是q指向之前的那个。 – Aaron