C 语言程序,用单链表来反序显示数字
链表用动态内存分配,是节点的集合。
节点有两部分,即数据和链接。
链表类型
C 编程语言中的链表类型如下 −
- 单向/单链表
- 双向/双链表
- 环形单链表
- 环形双链表
单链表
下图描述了单链表的表示。
示例
以下是用 C 程序通过单链表反序显示数字的示例 −
#include <stdio.h> #include <stdlib.h> struct node { int num; struct node *nextptr; }*stnode; void createNodeList(int n); void reverseDispList(); void displayList(); int main(){ int n; printf("
single Linked List : print it in reverse order :
"); printf("------------------------------------------------------------------------------
"); printf(" Input the number of nodes : "); scanf("%d", &n); createNodeList(n); printf("
Data entered in the list are :
"); displayList(); reverseDispList(); printf("
The list in reverse are :
"); displayList(); return 0; } void createNodeList(int n){ struct node *fnNode, *tmp; int num, i; stnode = (struct node *)malloc(sizeof(struct node)); if(stnode == NULL) { printf(" Memory can not be allocated."); } else{ // reads data for the node through keyboard printf(" Input data for node 1 : "); scanf("%d", &num); stnode-> num = num; stnode-> nextptr = NULL; tmp = stnode; //Creates n nodes and adds to linked list for(i=2; i<=n; i++){ fnNode = (struct node *)malloc(sizeof(struct node)); if(fnNode == NULL) { printf(" Memory can not be allocated."); break; } else{ printf(" Input data for node %d : ", i); scanf(" %d", &num); fnNode->num = num; fnNode->nextptr = NULL; tmp->nextptr = fnNode; tmp = tmp->nextptr; } } } } void reverseDispList(){ struct node *prevNode, *curNode; if(stnode != NULL){ prevNode = stnode; curNode = stnode->nextptr; stnode = stnode->nextptr; prevNode->nextptr = NULL; //convert the first node as last while(stnode != NULL){ stnode = stnode->nextptr; curNode->nextptr = prevNode; prevNode = curNode; curNode = stnode; } stnode = prevNode; //convert the last node as head } } void displayList(){ struct node *tmp; if(stnode == NULL){ printf(" No data found in the list."); } else{ tmp = stnode; while(tmp != NULL){ printf(" Data = %d
", tmp->num); tmp = tmp->nextptr; } } }
输出
当执行以上程序时,将产生以下结果 −
Single Linked List : print it in reverse order : ------------------------------------------------------------------------------ Input the number of nodes : 5 Input data for node 1 : 12 Input data for node 2 : 45 Input data for node 3 : 11 Input data for node 4 : 9 Input data for node 5 : 10 Data entered in the list are : Data = 12 Data = 45 Data = 11 Data = 9 Data = 10 The list in reverse are : Data = 10 Data = 9 Data = 11 Data = 45 Data = 12
广告