链表的插入与删除

插入:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct node
{
	int data;
	struct node *next;
}NODE;
NODE *create(int n)
{
	int a;
	NODE *head,*p,*q;
	head=NULL;
	while(n--)
	{
		scanf("%d",&a);
		p=(NODE *)malloc(sizeof(NODE));
		p->data=a;
		p->next=NULL;
		if(head==NULL)
		{
			head=p;
		}
		else
		{
			q->next=p;
		}
		q=p;
	}
	return head;
}
NODE *charu(NODE *head,int a)
{
	NODE *p,*q;
	int i,j,b;
	scanf("%d",&b);
	p=(NODE *)malloc(sizeof(NODE));
	p->data=b;
	q=head;//相当重要,保存头结点,
	if(a==1)
	{
		p->next=head;
		return p;
	} 
		for(i=1;i<a-1;i++)
		{
			head=head->next;//head=第a个结点的上一个结点
		}
		p->next=head->next;
		head->next=p;
		return q;
}
int main(void)
{
	int i,a,n;
	scanf("%d",&n);
	NODE *head;
	head=create(n);
	scanf("%d",&a);
	head=charu(head,a);
	while(head!=NULL)
	{
		printf("%d ",head->data);
		head=head->next;
	}
}

输入:

5
1 2 3 4 5
3 6

输出:

1 2 6 3 4 5

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

删除:

#include<stdio.h>
#include<stdlib.h>
struct node{
	int date;
	struct node *next;
};

struct node *create(int n)
{
	struct node *head,*p,*q;
	head = NULL;
	while(n--){
		p = (struct node *)malloc(sizeof(struct node));
		scanf("%d",&p->date);
		p->next = NULL; 
		if(head==NULL){
			head = p;
		} 
		else{
			q->next = p; 
		}
		q = p;
	} 
	return head;
}

struct node *shanchu(struct node *head,int a)
{
	int i;
	struct node *p,*q;
	q = head;
	p = head;
	if(a==1){
		head = head->next;
		return head;
	}
	for(i=1;i<a-1;i++){
		p = p->next;
	}
	q = p->next;
	p->next = q->next;
	free(q);
	return head; 
}

int main()
{
	int n,a;
	scanf("%d",&n);
	struct node *head;
	head = create(n);
	scanf("%d",&a);
	head = shanchu(head,a);
	while(head!=NULL){
		printf("%d ",head->date);
		head = head->next;
	}
} 

输入:

5
2 4 5 8 10
3

输出:

2 4 8 10

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值