链表的各种基本函数

/*	线性表基本操作的编程实现,掌握线性表的建立、遍历、插入、删除等基本操作的编程
实现,也可以进一步编程实现查找、逆序、排序等操作,需要实现线性表的以下功能:   
1、创建单链表    
2、删除链表中的某个结点     
3、输出单链表(遍历)     
4、释放结点所占空间   
5、查找第i个结点      
6、插入一个结点        
7、求链表的长度*/ 
#include
#include
#define LEN sizeof(struct node)
typedef struct node
{
	int num;
	struct node *next;
 }Node;

Node *create(int n)
{
	int i;
	Node *p,*prep,*head;
	if((head=p=prep=(Node *)malloc(LEN)) == NULL)
	{
		printf("Failure to apply for space");
		exit (0);
	}
	else
	{
		p->num = 1;
		for(i=1;i<n;i++)
		{
			if((p=(Node *)malloc(LEN)) == NULL)
			{
				printf("Failure to apply for space");
				exit (0);
			}
			else
			{
				p->num = i+1;
				prep->next=p;
				prep=p;
			}
		}
		p->next =NULL;
		return head;
	}
}

void show(Node *head)
{
	for(;head;head=head->next)
	printf("%4d",head->num);
	puts("");
}

Node *dlt(Node *head,int n)
{
	Node *p,*prep;
	for(p=prep=head;p;p=p->next)
	{
		if(p==head && p->num==n)
		{
			head=p->next;
			free(p);
			p=prep=head	;		//p被释放了,不能执行p=p->next 
		}
		else if(p->num == n)
		{
			prep->next=p->next;
			free(p);
			p=prep;
		}
		else
		prep=p;
	}
	return head;
}

Node *find(Node *head,int n)
{
	int i;
	for(i=1;i<n&&head;i++)
	head=head->next;
	return head;
}

Node *insert(Node *head,int n)
{
	Node *prep,*p;
	if((p=(Node *)malloc(LEN)) == NULL)
	{
		printf("Failure to apply for space");
		exit (0);
	}
	else 
	{
		p->num=n; 
		if(p->num<head->num)
		{
			p->next=head;
			head=p;
			return head;
		 } 
		for (prep=head ;prep->next&&(p->num)>(prep->next->num) ;prep=prep->next);
		p->next=prep->next;
		prep->next=p;
		return head;
		//如果判断写成(p->num)>(prep->next->num)&&prep->next,当它是倒数第二个时,prep->next->num就错了
	}
}

int callen(Node *head)
{
	int n=0;
	while(head)
	{
		head=head->next;
		n++;
	}
	return n;
}

int main()
{
	Node *head,*p;
	int n=3;
	head = create(10);
	show (head);
	head=dlt (head,3);
	show (head);
	printf("Please enter the position that you want to find: ");
	//scanf("%d",&n);
	if(p=find(head,n))
	printf("%d\n",p->num);
	else printf("The Position was exceeded");
	head = insert(head,0);
	show(head);
	printf("%d",callen(head));
}

你可能感兴趣的:(代码量)