C中的链表实现(仅打印最后两个节点)

时间:2017-06-24 13:48:07

标签: c linked-list append singly-linked-list

#include <stdlib.h>
#include <stdio.h>

struct node {
    int data;
    struct node *next;
};
void addLast(struct node **head, int value);
void printAll(struct node *head);
struct node *head1 = NULL;

int main() {
    addLast(&head1, 10);
    addLast(&head1, 20);
    addLast(&head1, 30);
    addLast(&head1, 40);    

    printAll(head1);

    return 0;
}

void addLast(struct node **head, int value) {
    struct node *newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = value;
    if (*head == NULL) {
        *head = newNode;
        (*head)->next = NULL; 
    } else {
        struct node **temp = head;

        while ((*temp)->next != NULL) {
            *temp = (*temp)->next;
        }
        (*temp)->next = newNode;
        newNode->next = NULL;
   }
}

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

addLast()会将新节点附加到列表末尾,printAll(),我正在打印整个列表。

每次打印列表时,我只能看到最后两个节点。

任何人都可以请求帮助,为什么循环不会遍历整个列表?

1 个答案:

答案 0 :(得分:1)

函数addLast过于复杂,由于此声明而导致错误

*temp = (*temp)->next;
在while循环中

。它总是改变头节点。

按以下方式定义功能

int addLast( struct node **head, int value )
{
    struct node *newNode = malloc( sizeof( struct node ) );
    int success = newNode != NULL;

    if ( success )
    {
        newNode->data = value;
        newNode->next = NULL:

        while( *head ) head = &( *head )->next;

        *head = newNode;
    }

    return success;
}

考虑到没有必要将变量head1声明为全局变量。最好在函数main中声明它。

在退出程序之前,还应释放所有已分配的内存。