实现简单链接列表

时间:2014-02-14 17:59:48

标签: c pointers linked-list

您好我希望将一个简单的链接列表和所有值实现到列表的末尾。就这么简单,但我无法这样做。你能告诉我我做错了吗?最初我声明一个指针并为其分配NULL值。稍后在每次迭代中,我将内存分配给最初为NULL的指针。

#include <stdio.h>
#include <malloc.h>

struct node{
    int a;
    struct node* next;
};
struct node* insert(struct node* start,int value);
void print(struct node* head);
int main()
{
    int a;
    struct node* head = NULL;
    while(scanf("%d",&a) != EOF)//taking input
    {
        head = insert(head,a);
        print(head);
    }
    return 0;
}

struct node* insert(struct node* start,int value)
{
    struct node* head = start;
    while(start != NULL)
    {
        start = start->next;//getting upto the end of the linked list
    }
    start = (struct node*)malloc(sizeof(struct node));//allocating memory at the end
    start->a = value;
    start->next = NULL;
    if(head == NULL) 
    {
        return start;//for the base case when list is initally empty
    }
    return head;
}

void print(struct node* head)
{
    while(head != NULL)
    {
        printf("%d\n",head->a);
        head = head->next;
    }
    return;
}

2 个答案:

答案 0 :(得分:1)

您的尾部和新节点之间的联系正在丢失,请尝试使用

struct node* insert(struct node* head,int value)
{
struct node* tail = head;
while(tail != NULL && tail->next != NULL)
{
    tail= tail->next;//getting upto the end of the linked list
}

struct node* start = (struct node*)malloc(sizeof(struct node));//allocating memory at the end
start->a = value;
start->next = NULL;
if(head == NULL) 
{
    return start;//for the base case when list is initally empty
}
else
{
    tail->next = start;
}
return head;
}

答案 1 :(得分:0)

struct node* insert(struct node* start,int value){
    struct node* head = start;
    struct node* np = (struct node*)malloc(sizeof(struct node));
    np->a = value;
    np->next = NULL;

    if(head == NULL)
        return np;

    while(start->next != NULL){
        start = start->next;
    }
    start->next = np;
    return head;
}

我使用越野车的方法是什么原因?

nodeX
|
+a
|
+next(address to OtherX)

nodeX.next = new_node;//update link(case of OK)

tempPointer = nodeX.next;//address to OtherX set to tempPointer
tempPointer = new_node;//contents of tempPointer changed, but orignal (nodeX.next not change)
相关问题