`
hufeng
  • 浏览: 100990 次
  • 性别: Icon_minigender_1
  • 来自: 江西
社区版块
存档分类
最新评论

c语言之链表学习

阅读更多

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAX 1000

/* 编一C程序,它能读入两组整数(每组整数都以-9999为结束标记,个数都不大于1000),
并以从小到大的次序输出既在第一组整数中也在第二组整数中的所有整数(同一个整数不能输出两次)。
(输入时,两个相邻的整数用空格隔开)。*/

/*它能读入一串整数(以-9999为结束标记),再以与输入次序相反的次序输出这串整数(输入、出时,两个相邻的整数用空格隔开)*/

typedef struct Node
{
	int d;
	struct Node *next;
}NODE,*PNODE;

void printLinkList(PNODE head)
{
	PNODE p = head;
	while((p=p->next)!=NULL)
	{
		printf("%d ",p->d);
	}
}
//初始化链表 课本上
PNODE initLinklist()
{
	PNODE head,tail,p;
	int n;
	head = (PNODE)malloc(sizeof(NODE));
	tail=head;
	scanf("%d",&n);
	while(n!=-9999)
	{
		p = (PNODE)malloc(sizeof(NODE));

		p->d=n;
		tail->next=p;
		tail=p;
		scanf("%d",&n);
	}
	tail->next=NULL;
	return head;
}


PNODE initLinklist2()
{
	PNODE head,h,p;
	int d;
	head=h=(PNODE)malloc(sizeof(NODE));
	scanf("%d",&d);
	if(d==-9999)return head;
	do
	{
		p =(PNODE)malloc(sizeof(NODE));
		p->d=d;
		p->next=NULL;
		h->next=p;
		h=p;
		scanf("%d",&d);
	}while(d!=-9999);
	return head;
}
//初始化链表,输入 12345 打印54321
PNODE initLinklist3()
{
	PNODE head,tail;
	int d;
	head=(PNODE)malloc(sizeof(NODE));
	head->next=NULL;
	scanf("%d",&d);
	if(d==-9999)return head;
	do
	{
		tail =(PNODE)malloc(sizeof(NODE));
		tail->d=d;
		if(head->next==NULL)
		{
			head->next=tail;
			tail->next=NULL;
		}
		else
		{
			tail->next=head->next;
			head->next=tail;
		}
		scanf("%d",&d);
	}while(d!=-9999);
	return head;
}



//冒泡排序
PNODE maopaoSort(PNODE head)
{
	PNODE p1,p2;
	int temp;
	p1=head->next;
	for(;p1;p1=p1->next)
	{
		for(p2=p1->next;p2;p2=p2->next)
		{
			if(p2->d<p1->d)
			{
				temp=p2->d;
				p2->d=p1->d;
				p1->d=temp;
			}
		}
	}
	return head;
}




void deleteDuplicate(PNODE n){
	while(n)
	{
		n=n->next;
		if(n&&n->next&&n->d==n->next->d)
		{
		 n->next=n->next->next;
		}
	}
}
//前提已经排序
void deleteNoDuplicate(PNODE head)
{
	PNODE p;
	p=head->next;
	while(p)
	{
		if(p->next&&p->d==p->next->d)
		{
			p->next=p->next->next;//本应该考虑内存释放

		}
		p=p->next;

	}
}
/*
插入排序
*/

void insertSort1(PNODE head)
{
	PNODE h,p1,p2;
	if(!head->next||!head->next->next)return;
	h=head;
	p2=head->next->next;//第二个链表的起始地址
	h->next->next=NULL;//第一个节点指向NULL,链表分段
	while(p2)
	{
		p1=p2->next;
		h=head;//h归位
		while(h->next)
		{
			if(h->next->d>p2->d)
			{
				p2->next=h->next;
				h->next=p2;
				break;
			}
			else
			{
				h=h->next;
			}
		}
		if(h->next==NULL)
		{
			h->next=p2;
			p2->next=NULL;
		}
		p2=p1;//P2归位
	}

}
void main()
{
	PNODE a;
	printf("input a:\n");
	a = initLinklist3();
	printLinkList(a);
	printf("\n");
	maopaoSort(a);
	printLinkList(a);
	//deleteNoDuplicate(a);
	//printLinkList(a);
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics