2019年12月第二周--------链表

1.什么是链表:

链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
​ 这里需要两个头文件

#include<stdio.h>
#include<stdlib.h>

2.链表的相关操作:

1.链表的创建:
struct node{
	int date;
	struct node *next;
};
int main()
{
	int n,a,find,add,del;
	scanf("%d",&n);
	struct node *head,*p,*q,*t1,*t2,*t3,*t4;
	head=NULL;
	for(int i=0;i<n;++i){
		scanf("%d",&a);
		p=(struct node*)malloc(sizeof(struct node));
		p->date=a;
		p->next=NULL;
		if(head==NULL)
			head=p;
		else
			q->next=p;
		q=p;
	} ;
2.所需要的函数声明:
1.链表的查找:
	t2=head;//查找 
	scanf("%d",&find);
	while(t2!=NULL){
		if(t2->date==find){
			printf("%d",t2->date);
			break;
		}
		t2=t2->next;
	}
	if(t2==NULL)
		printf("NO");
2.链表的增添:

	scanf("%d",&add);
	while(t3!=NULL){
		if(t3->next==NULL||t3->next->date>= add){
			p=(struct node*)malloc(sizeof(struct node));
			p->date=add;
			p->next=t3->next;
			t3->next=p;			
			break;
		}
		t3=t3->next;
	}
	//或者
		for(t3=head;t3!=NULL;t3=t3->next){链表的增添 
		if(t3->next==NULL||t3->next->date>add){
			p=(struct node*)malloc(sizeof(struct node));
			p->date=add;
			p->next=t3->next;
			t3->next=p;
			break;
		}
	}
3.链表删除:

	scanf("%d",&del);//删除 
	for(t3=head;t3!=NULL;t3=t3->next){
		
		if(t3->next->date==del){
			t3->next=t3->next->next;
		
			break;
		}
	}
4.链表输出
	t1=head;
	while(t1!=NULL){
		printf("%d ",t1->date);
		t1=t1->next;
	}
4.链表逆置的方法:
1.头插法

​ 遍历一次链表,在遍历的过程中将遍历到的节点头插至新的链表中

    head= (struct node*)malloc(sizeof(stuct node));
    head->next = NULL;
    struct node *s;
    int x;

    while(scanf("%d",&x) && x!= -1) {
        s = (struct node*)malloc(sizeof(struct node));
        s->data = x;
        s->next = head->next;
        head->next = s;
    }

    return head;
}
	2.就地逆置

    struct node *p,*q;
    p = head->next;
   head->next = NULL;
    while(p) {
        q = p;
        p = p->next;
        q->next = head->next;
        head->next = q;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值