如何给链表录入数据

如何给链表录入数据,第1张

struct Node

{

int value

struct Node *next

}

1.先建立链表。

2.数据录入

void inputdata(Node *head)

{

Node *p

int num

p = head

while(cin>>num &&p != NULL)

{

p->value = num

p = p->next

}

}

这是一个简单的C建立单链表程序,可以供你参考学习。

#include <iostream.h>

#include <stdio.h>

#include <stdlib.h>

typedef struct node

{

int date

struct node *next

}slnode,*Linklist

void creat_list(Linklist H)//创建链表,由于实参传值使L指向了一个空节点从而成为头节点指针

{

Linklist p, p1

int n

cout<<"请输入结点数"<<endl

cin>>n

H->date=n

cout<<"请输入结点数据"<<endl

p1 = H//使p1具有了空间

for(int i=0i<ni++)

{

p=(Linklist)malloc(sizeof(slnode))

p->next = NULL

cin>>p->date

H->next = p

H=p//L指向了最后节点的数据域

}

H=p1//使尾指针指向了最后节点的数据域

}

void display_list(Linklist H)//输出链表

{

cout<<"输出"<<endl

Linklist p

p = H->next

for(int i=0i<H->datei++)

{

cout<<p->date

cout <<' 'cout<<'\n'

p = p ->next

}

}

void main()

{

slnode a//a是空结构变量

Linklist p//p是指针

p = &a//p指向了一个空节点

creat_list(p)//传的是结构变量的地址

display_list(p)

}

#include "stdio.h"

#include "stdlib.h"

#include "string.h"

typedef struct

{

int num

char name[10]

int grade

}student

typedef struct node

{

student date

struct node *next

}*link

link head = NULL

student creat(void)

{

student p

printf("请输入学生学号:")

setbuf(stdin,(char *)0)

scanf("%d",&p.num)

printf("请输入学生名字:")

setbuf(stdin,(char *)0)

scanf("%s",p.name)

printf("请输入学生成绩:")

setbuf(stdin,(char *)0)

scanf("%d",&p.grade)

return p

}

void insert(student date)

{

link p = (struct node*)malloc(sizeof *p)

p->date=date

p->next=head

head=p

}

void output(void)

{

link p = head

printf("|----学号-----姓名-------成绩--|\n")

while(p!=NULL)

{

printf("|%-9d%-11s%-6d|\n",p->date.num,p->date.name,p->date.grade)

p=p->next

}

printf("|------------------------------|\n")

}

void init(void)

{

puts("*************欢迎使用信息查询系统*************")

puts("*\t+-------------------------+*")

puts("*\t| 1.添加记录|*")

puts("*\t| 2.显示所有记录|*")

puts("*\t| 0.保存退出|*")

puts("*\t+-------------------------+*")

puts("********************************************")

printf("\t请输入您的选择:")

}

int main()

{

int n

char cmd[10]

do{

//system("cls")

men:init()

setbuf(stdin,(char *)0)//清空输入流

scanf("%[^\n]",cmd)//接受除换行以外的所有字符存入cmd中,并加上'\0'标志

sscanf(cmd,"%d",&n)

/*处理当命令不符合条件的情况*/

if(strlen(cmd) != 1 || n <0 || n >2 || !(*cmd >= '0' &&*cmd <= '2'))

{

printf("\t输入错误或没有这个选项!")

getchar()

getchar()

goto men

}

switch(n)

{

case 1:insert(creat())puts("\t添加成功!")break

case 2:output()break

case 0: return 0

default :break

}

printf("\tPress Enter To Continue!")

getchar()

getchar()

}while(n != 0)

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11792710.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存