C 语言程序,用于创建并显示单向链表


2022年5月12日, Learn eTutorial
1296

什么是链表?

在这个 C 语言程序中,我们需要创建一个链表并显示列表中的元素。链表简单来说就是一组动态分配的节点,每个节点包含一个值和一个指针。换句话说,链表是使用指针实现动态数据结构的最好例子。然后我们还需要了解链表在 C 语言程序中的表示方式。一个指针表示链表中的第一个节点。换句话说,链表是使用链接连接的数据结构序列。每个链接都包含与其他链接的连接。它是仅次于数组最常用的数据结构。在 C 语言中,链表可以使用结构体和指针来实现。

struct LinkedList
{
int data;
struct linkedlist *next;
};

如何在 C 语言中创建链表?

该 C 语言程序的逻辑是声明一个结构体节点,其中包含成员 num 和一个指针 **ptr**,并将 **choice = 1**。使用条件为 **choice!=0** 的 `while 循环`,通过 **malloc** 函数动态创建头节点。将数据项读取到变量 head->num 中。检查 first 是否不等于零,然后 temp->ptr=head,temp=head,否则设置 first=temp=head。然后从用户读取 choice 并重复循环,使用 `for 循环` 显示链表。最后,显示列表的计数为 count。

算法

步骤 1:包含头文件,以便在 C 程序中使用内置头文件。

步骤 2:声明包含成员 **num,*ptr** 的结构体节点。

步骤 3:声明变量 **NODE** 为类型 **node,*head,*first,*temp=0**。

步骤 4:设置 **count=0,choice=1,first=0**。

步骤 5:使用条件为 choice 为真的 `while 循环`,然后执行步骤 6。

步骤 6:设置 **head=(NODE*)** malloc(sizeof(NODE))。

步骤 7:将数据项读取到变量 **head->num** 中。

步骤 8:检查 `if` **first!=0**,然后 **temp->ptr=head**,**temp=head**。`否则` 执行步骤 9。

步骤 9:赋值 **first=temp=head**。

步骤 10:读取用户的选择,他们是想继续还是退出,并重复步骤 5。

步骤 11:在 `while 循环` 结束时,设置 **temp->ptr = 0**,**temp=first**。

步骤 12:显示链表的状态。

步骤 13:使用条件为 **temp!=0** 的 `while 循环`,然后显示 **temp->num**,然后将 count 增加 1。

步骤 14:赋值 **temp=temp->ptr**。

步骤 15:显示列表中节点的数量为 **count**。

C 语言源代码

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

void main() {
  struct node {
    int num;
    struct node * ptr;
  };
  typedef struct node NODE;
  NODE * head, * first, * temp = 0;
  int count = 0;
  int choice = 1;
  first = 0;
  while (choice) {
    head = (NODE * ) malloc(sizeof(NODE));
    printf("Enter the data item\n");
    scanf("%d", & head-> num);
    if (first != 0) {
      temp -> ptr = head;
      temp = head;
    } else {
      first = temp = head;
    }
    fflush(stdin);
    printf("Do you want to continue(Type 0 or 1)?\n");
    scanf("%d", & choice);
  } /* End of while */ 
  temp = first; /* reset temp to the beginning*/
  printf("\nstatus of the linked list is\n");
  while (temp != 0) {
    printf("%d=>", temp -> num);
    count++;
    temp = temp -> ptr;
  }
  printf("NULL\n");
  printf("No. of nodes in the list = %d\n", count);
} /* End of main*/
                                      

输出

Enter the data item
10

Do you want to continue(Type 0 or 1)?
1

Enter the data item
34

Do you want to continue(Type 0 or 1)?
1

Enter the data item
56

Do you want to continue(Type 0 or 1)?
0

status of the linked list is
10=>34=>56=>NULL
No. of nodes in the list = 3