数据结构 - 复习(链表部分)

1.反转链表

list reverse(list l)
{
	list new_node,old_node,temp;
	old_node = l;
	new_node = NULL;
	while(old_node)
	{
		temp = old_node->next;//临时变量指向第一个节点的后面
		old_node->next = new_node;//第一个节点往后指
		new_node = old_node;
		old_node = temp;
	}
	l = new_node;
	return l;
}

2.线性表的顺序存储(以数组为中心)

<1>初始化

list makeempty()
{
	list l;
	l = (list)malloc(sizeof(struct node));
	l->next = -1;
	return l;
}

<2>查找

int find(list l,int data)
{
	int i = 0;
	while(i<=l->next&&data[i]!=data)
		i++;
	if(i>l->next)
		return -1//没有找到
	else 
		return i; 
}

<3>插入

bool insert(list l,int x, int i)//分别为线性表,需要插入的元素,需要插入的位置
{
	if(l->next == maxn - 1)//代表满了
		return 0;
	if(i<=0||i>l->next + 2)//插入的位置不合法 
		return 0; 
	for(int j = l->next; j >=i-1; j --)
	{
		l->data[j+1] = l->data[j];
	}
	l->data[i-1] = x;
	l->next ++;
	return 1;
 } 

<4>删除

bool Delete(list l,int i)
{
	if(i<1||i>l->next + 1)
		return 0;
	if(l==NULL)
		return 0;
	for(int j = i; j <= l->next; j ++)
		l->data[j-1] = l->data[j]; 
	l->next --;
	return 1;
 } 

3.线性表的链式存储

<1>计算长度

int lenth(list l)
{
	int cnt = 0;
	while(l)
	{
		l = l->next;
		cnt++; 
	}
	return cnt;
}

<2>查找(按位置查找)

int find(list l,int k)
{
	int cnt = 1;
	while(l&&cnt<k)
	{
		l = l->next;
		cnt++;
	}
	if(cnt<k)
		return 0;
	else
		return l->data;
	
}

查找(按值查找)

int find(list l,int x)
{
	int flag = 0;
	while(l)
	{
		if(l->data == x)
		{
			flag = 1;
			break;
		}
		l = l->next;
	} 
	return flag;
 } 

<3>插入(无头结点)

list insert(list l,int x,int i)
{
	list temp;
	temp = (list)malloc(sizeof struct node);
	temp->data = x;
	if(i==1)
	{
		temp->next = l;
		return temp;
	}
	int cnt = 1;
	list pre;
	pre = l;
	while(pre&&cnt<i)
	{
		cnt++;
		pre = pre->next;
	}
	if(pre==NULL||cnt!=i-1)
		return 0;
	else
	{
		temp->next = pre->next;
		pre->next = temp;
		return l;
	}
}

插入(有头结点)

bool insert(list l,int x, int i)
{
	list temp,pre;
	int cnt = 0;
	pre = l;
	while(pre&&cnt<i-1)
	{
		pre = pre->next;
		cnt++;
	}
	if(pre==NULL||cnt!=i-1)
		return 0;
	else
	{
		temp = (list)malloc(sizeof pre);
		temp->data = x;
		temp->next = pre->next;
		pre->next = temp;
		return 1;
	}
 } 

<4>删除(带头节点)

bool Delete(list l,int i)
{
	list temp,pre;
	int cnt = 0;
	pre = l;
	while(pre&&cnt<i-1)
	{
		pre = pre->next;
		cnt++;
	}
	if(pre==NULL||cnt!=i-1||pre->next == NULL)
		return 0;
	pre->next = pre->next->next;
	return 1; 
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值