link.cpp
来自「一些VC++的经典实例」· C++ 代码 · 共 72 行
CPP
72 行
//Program ex12 数据结构基础,构造单链表
#include "stdio.h"
#include "conio.h"
#define N 5
struct Node
{
int num;
struct Node * next;
};
void insert(struct Node *head,struct Node * p)
{
struct Node * tmp;
struct Node * pre;
if(head->next==NULL)
{
head->next=p;
p->next=NULL;
}
else
{
pre=tmp=head;
while(tmp=tmp->next)
{
if(tmp->num>=p->num)
break;
else
{
pre=tmp;
}
}
pre->next=p;
p->next=tmp;
}
}
void display(struct Node * head)
{
struct Node * p=head;
while(p=p->next)
{
printf("当前节点的值为:%d\n",p->num);
}
}
int main(void)
{
int i;
printf("**************************************\n");
printf("* 本程序实现单链表的初始化/插入/遍历 *\n");
printf("**************************************\n");
struct Node * head=new Node;
struct Node * p=head;
head->next=NULL;
for(i=0;i<5;i++)
{
printf("请输入第%d个节点的数据:",i+1);
p=new Node;
scanf("%d",&(p->num));
insert(head,p);
}
display(head);
return 1;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?