/***********************************************
* 作者 :skywalker_prime
* 联系方式 :shanquan54@163.com
* 最后修改时间 :2015-08-04 21:41
* 文件名称 :1.c
* 程序描述 :
* csdnd地址 :blog.csdn.net/skywalker_prime
***********************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LENGTH sizeof(struct student)
int n=0;
typedef struct student
{
int num;
struct student *next;
}stu;
stu *create()
{
stu *head=NULL;
stu *p1=NULL;
stu *p2=NULL;
stu *p=NULL;
char judge;
if(head==NULL)
{
printf("create a new node(y/n) ?\n");
judge=getchar();
while(getchar()!='\n');
if(judge=='y')
{
printf("please input num data:");
p=malloc(LENGTH);
scanf("%d",&p->num);
while(getchar()!='\n');
head=p2=p1=p;
head->next=NULL;
n++;
}
}
while(1)
{
p1=p2=head;
printf("create a new node(y/n) ?\n");
judge=getchar();
while(getchar()!='\n');
if(judge=='y')
{
printf("please input num data:");
p=malloc(LENGTH);
scanf("%d",&p->num);
while(getchar() !='\n');
if(head==NULL)
{
head=p;
head->next=NULL;
n++;
}
else
{
if(p->num<head->num)
{
p1=head;
head=p;
head->next=p1;
n++;
}
else
{
while(p->num > p1->num && p1->next != NULL )
{
p2=p1;
p1=p1->next;
}
if(p->num > p1->num)
{
p1->next=p;
p1=p;
p1->next=NULL;
n++;
}
else
{
p2->next=p;
p->next=p1;
n++;
}
}//else
}//else
}//if judge=='y'
else
{
break;
}//while(1)
}
return head;
}
#if 1
void print1(stu *head)
{
stu *p;
p=head;
while(p!=NULL)
{
printf("%d\t",p->num);
p=p->next;
}
}
#endif
#if 1
void findmid(stu *head)
{
int flag=0;
stu *p1=NULL,*p2=NULL;
p1=head;
p2=head;
while(p2->next!=NULL)
{
if(p2->next->next!=NULL)
{
p2=p2->next->next;
}
else
{
flag=1;
break;
}
p1=p1->next;
}
printf("\n中间指针指向为:\n");
printf(" %d ",p1->num);
if(flag)
printf("and %d",p1->next->num);
printf("\n");
}
#endif
int main()
{
stu *head=NULL;
head=create();
printf("打印指针所指向数值:\n");
print1(head);
findmid(head);
return 0;
}
运行结果显示:
<pre name="code" class="objc">create a new node(y/n) ?
y
please input num data:1
create a new node(y/n) ?
y
please input num data:5
create a new node(y/n) ?
y
please input num data:13
create a new node(y/n) ?
y
please input num data:2
create a new node(y/n) ?
y
please input num data:9
create a new node(y/n) ?
n
打印指针所指向数值:
1 2 5 9 13
中间指针指向为:
5
单项链表的创建,打印,以及中间节点指向问题
最新推荐文章于 2022-01-12 15:59:45 发布