單項鍊表的創建,打印,以及中間節點指向問題

/***********************************************
 * 作者			:skywalker_prime
 * 聯繫方式 	:[email protected]
 * 最後修改時間	: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 



發佈了22 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章