while(x!=9999){ s = (LNode *)malloc(sizeof(LNode)); s->data = x; r->next = s; r = s; cin>>x; }
时间: 2024-05-19 11:15:58 浏览: 10
This code reads in a series of integers from the user until the value 9999 is entered. For each integer entered, a new node is created with the integer as its data value. The new node is then added to the end of a linked list. The variable "r" keeps track of the last node in the list and is updated each time a new node is added. The input value is stored in the variable "x" and is read in using the "cin" function from the C++ standard library.
相关问题
//初始化单链表 bool InitList(Lnode *L){ L=(Lnode*)malloc(sizeof(Lnode)); L->next=NULL; if(L==NULL)//内存不足,头结点无法分配到空间 return false; return true; } //(头插法)创建单链表 void CreateListF(Lnode *L,ElemType a[],int n){ Linklist s; L=(Lnode*)malloc(sizeof(Lnode)); L->next=NULL; int j=-0; for(j=0;j<n;j++){ s=(Lnode *)malloc(sizeof(Lnode)); s->data=a[j]; s->next=L->next; L->next=s; } } /* //(尾插法)创建单链表 void CreateListR(Lnode *L,ElemType a[],int n){ Linklist s, r; L=(Lnode*)malloc(sizeof(Lnode)); r=L; int i=0; for(i=0;i<n;i++){ s=(Lnode*)malloc(sizeof(Lnode)); s->data=a[i]; r->next=s; r=s; } r->next=NULL; } //判断链表是否为空 bool ListEmpty(Lnode *L){ return (L->next==NULL); } */ //输出链表 void DispList(Lnode *L){ Lnode* p=L->next; while(p!=NULL){ printf("%d",p->data); p=p->next; } printf("\n"); }
这段代码中包含了几个函数用于处理单链表。
1. `bool InitList(Lnode *L)`: 这个函数用于初始化单链表。它接受一个指向链表头结点的指针 L。在函数内部,它首先分配一个头结点的内存空间,并将其地址赋给 L。然后,将头结点的指针域 L->next 设置为 NULL,表示链表为空。最后,如果分配内存失败,返回 false;否则,返回 true。
2. `void CreateListF(Lnode *L,ElemType a[],int n)`: 这个函数使用头插法创建单链表。它接受一个指向链表头结点的指针 L,一个元素数组 a,以及元素个数 n。在函数内部,它首先分配一个头结点的内存空间,并将其地址赋给 L。然后,使用循环将数组中的元素依次插入到链表的头部。具体操作是:分配一个新节点 s,并将数组中的元素赋值给 s->data;然后,将新节点 s 插入到头结点之后,即 s->next = L->next,L->next = s。最后,循环结束后,完成链表的创建。
3. `void DispList(Lnode *L)`: 这个函数用于输出链表的元素值。它接受一个指向链表头结点的指针 L。在函数内部,它使用循环遍历链表的个节点,从头结点的下一个节点开始,直到遍历到链表末尾(即指针 p 指向 NULL)。在循环中,首先使用 printf 函数输出当前节点的数据值 p->data,然后将指针 p 移动到下一个节点 p->next。最后,在循环结束后,使用 printf 函数输出一个换行符,以便输出结果的格式化。
需要注意的是,代码中还有一些被注释掉的函数,包括 `CreateListR` 和 `ListEmpty`。这些函数分别用于使用尾插法创建单链表和判断链表是否为空。由于这些函数被注释掉了,所以在代码中并不会被调用到。
LinkList List_HeadInsert(LinkList &L){ LNode *s; int x; L=(LinkList)malloc(sizeof(LNode)); L->next=NULL; scanf("%d",&x); while(x!=9999){ s=(LNode *)malloc(sizeof(LNode)); s->data=x; s->next=L->next; L->next=s; scanf("%d",&x); } }
可以理解为一个带有参数的函数声明,其中LinkList是一个链表的类型名称,在这个函数中需要传入一个LinkList类型的参数List_HeadInsert,表示要对这个链表进行头插法的操作。更具体地说,头插法是指将新节点插入到链表头部,使其成为新的头结点,而原有的头结点则向后移动。这个函数可以用于创建一个新的链表,也可以用于向一个已有链表中插入新节点。