初始化一个链表并遍历链表

#include <stdio.h>
#include <stdlib.h>  // 用于 malloc 和 free

// 定义链表结点结构体
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 初始化链表(返回头指针)
Node* initList() {
    return NULL;  // 初始时链表为空
}

// 向链表尾部插入新结点
void insertAtEnd(Node** headRef, int value) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (!newNode) {
        printf("内存分配失败!\n");
        exit(1);
    }
    newNode->data = value;
    newNode->next = NULL;

    if (*headRef == NULL) {
        *headRef = newNode;  // 如果链表为空,新结点成为头结点
    } else {
        Node* current = *headRef;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;  // 插入到链表尾部
    }
}

// 遍历链表并打印所有结点的值
void traverseList(Node* head) {
    Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

// 主函数测试
int main() {
    Node* head = initList();  // 初始化链表

    // 向链表中插入一些结点
    insertAtEnd(&head, 10);
    insertAtEnd(&head, 20);
    insertAtEnd(&head, 30);
    insertAtEnd(&head, 40);

    // 遍历链表
    printf("链表内容:\n");
    traverseList(head);

    // 释放内存(可选,实际开发中建议添加)
    Node* current = head;
    while (current != NULL) {
        Node* temp = current;
        current = current->next;
        free(temp);
    }

    return 0;
}

自己重写一遍找错误

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
	int data;
	struct Node *next;
}Node;
Node *initiList()
{
	return NULL;
}
void insertAtEnd(Node** headRef,int value)
{
	Node* newnode=(Node*)malloc(sizeof(Node));
	if(!newnode)
	{
		printf("内存分配失败\n");
		exit(1);
	 } 
	newnode->data=value;
	newnode->next=NULL;
	if(*headRef==NULL)
	{
		*headRef=newnode;
	}
	else
	{
	 Node* current=*headRef;
	 while(current->next!=NULL)
	 {
	 	current = current->next;
	 }
	 current->next=newnode;
	}
	
}
void traverseList(Node *head)
{
	Node* current=head;
	while (current != NULL)              //different frominsert函数中while(current->next!=NuLL)
	{
		printf("%d->",current->data);
		current = current->next;
	}
	printf("NULL\n");
}
int main()
{
	Node* head=initiList();
	insertAtEnd(&head,40);
	insertAtEnd(&head,54);
	insertAtEnd(&head,56);              //误打成insertAtEnd
	traverseList(head);
	Node* current=head;
	while(current != NULL)
	{
		Node* temp=current;
		current=current->next;
		free(temp);
	}
	return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务