您的位置:首页 > 其它

链表建立、删除、插入基本操作

2013-07-29 12:05 357 查看
在数据结构中,链表无疑是最基本的,也是在大多数IT公司面试笔试中考察最多的;有了扎实的处理链表的基础,对以后学习更复杂的数据结构类型是很有帮助也是很有必要的;因此在闲暇时间中,又再一次重写了对于链表的一些基本操作,也参考了一些资料,在此将代码分享一下,希望对初学者有所帮助。

一开始的时候,对于链表的建立,都会这样来写,基本上都会用到两次malloc函数的调用。代码大致上如下所示。

//创建长度为n的单链表
node *create(int n)
{
	node *head,*precious,*current;
	int cnt;
	int label = 1;
	for(cnt = 0;cnt < n;cnt++)
	{
		if(label == 1)
		{
			precious = (node *)malloc(sizeof(node));
			printf("Input the information just like:name ID gender age \n");
			scanf("%s%s%s%d",precious->name,precious->ID,precious->s,&precious->age);
			precious->link = NULL;
			head = precious;
			label = 0;
		}
		else
		{
			current = (node*)malloc(sizeof(node));
			printf("Input the information just like:name ID gender age \n");
			scanf("%s%s%s%d",current->name,current->ID,current->s,¤t->age);
//			current->link = NULL;
			precious->link = current;
			precious = current;
		}		
	}
	precious->link = NULL;
	return head;
}


后来看了一些资料,简化了很多,下面这种写法值得提倡:

//建立链表
node *CreatLink(int n)
{
	node *head,*p,*q;

	for(int i=1; i<n+1; i++)
	{
		p = (node*)malloc(sizeof(node));
		printf("input a number:");
		scanf("%d",&p->data);

		if(i == 1) head = p;
		else q->next = p;

		q = p;
		p->next = NULL; 
	}

	return head;
}


然后要提到的就是插入和删除的操作了:有两点要注意:首先不论是插入还是删除第一要做的就是找到要操作的那个位置;其次要把操作的位置分三种情况,即头结点、中间结点、尾结点。
下面的代码参考了一些资料(如程序员面试宝典、谭浩强的书)

插入结点

node *Insert(node *head,int num)
{
	node *p,*q,*s;
	s = (node*)malloc(sizeof(node));
	printf("input a number:");
	scanf("%d",&s->data);
	p = head;
	//先寻找到相应位置再处理,假设数据已按升序排列
	while(p->data < s->data && p->next != NULL)
	{
		q = p; p = p->next;
	}

	if(p == head) {head = s; p = s->next;}
	else if(p->next == NULL) { p->next = s; s->next = NULL; }
	else { q->next = s; s->next = p; }

	return head;
}


删除结点:(可以将尾结点和中间结点步骤合二为一)

node *Delete(node *head,int num)
{
	node *p,*q;
	p = head;
	//先查找再删除
	while(p->data != num && p->next != NULL)
	{
		q = p; p = p->next;
	}

	if(num == p->data)
	{
		if(p == head) { head = p->next; free(p); }
		else { q->next = p->next; free(p); }
	}
	else
		printf("%d could not been found",num);

	return head;
}


最后简单再介绍一下链表排序,链表排序,重点在排序,对指针的操作少;而排序用到的无非就是几种经典的排序算法,如冒泡、直接、选择等等。通过我个人的经历来看,排序对于面试笔试来说也是个重点,几乎都能被问到。

以下是一个用冒泡法写的一个链表排序

node *Sort(node* head,int length)
{
	node *p;
	

	for(int i = 1; i < length ; i++)
	{
		p = head;
		for(int j = 0; j < length - i ; j++)
		{
			if(p->data > p->next->data)
			{
				int tmp = p->data;
				p->data = p->next->data;
				p->next->data = tmp;
			}
			p = p->next;
		}
	}

		return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐