(啊哈!算法)(第二章)链表

//链表的创建与插入值
#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

struct node{//定义链表节点 
	int data;
	struct node *next;
};

int main()
{
	struct node *head,*q,*p;//需要一个头指针,一个中间变量,一个临时变量 
	head=NULL;
	int ss;
	//创建链表 
	for(int i=0;i<5;i++){
		scanf("%d",&ss);
		q=(struct node*)malloc(sizeof(struct node));
		q->data=ss;
		q->next=NULL;
		if(head==NULL){
			head=q;
		}else{
			p->next=q;
		}
		p=q;
	}
	//打印链表 
	struct node*t;
	t=head;
	while(t!=NULL){
		printf("%d ",t->data);
		t=t->next;
	}
	printf("\n");
	//插入值 
	int temp=6;
	t=head;
	while(t!=NULL){
		if(t==NULL||t->next->data>temp){
			struct node*base;
			base=(struct node*)malloc(sizeof(struct node));
			base->data=temp;
			base->next=t->next;//顺序问题一定不能颠倒 
			t->next=base;
			break;
		}
		t=t->next;
	}
	//打印链表 
	t=head;
	while(t!=NULL){
		printf("%d ",t->data);
		t=t->next;
	}
	return 0;
}

 

链表必须掌握指针,因为模拟链表毕竟有局限性,

 

malloc函数的返回类型是void*类型,void*表示未确定类型的指针,void*可以转化为任意类型的指针

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值