链表基础操作

一、插入

1.头插法

#include<stdio.h>
#include<stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};
struct Node* head;
void Print()//打印链表 
{
    struct Node* temp=head;
    printf("List is: ") ;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}

void Insert(int x)
{
    struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
    temp->data=x;
    temp->next=head;
    head=temp;

}
int main()
{
    head=NULL;
    int n,x;
    printf("How many numbers do you want to input?\n");
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        printf("Pleasse input the number:\n");
        scanf("%d",&x);
        Insert(x);
        Print();
    }
    return 0;
}

2.在任意位置插入

void Insert(int x,int n) 
{
	struct Node* temp1=(struct Node*)malloc(sizeof(struct Node));
	temp1->data=x;
	temp1->next=NULL;
	if(n==1)
	{
		temp1->next=head;
		head=temp1;
		return;
	}
	Node* temp2=head;
	for(int i=0;i<n-2;i++)
	{
		temp2=temp2->next;
	}
	temp1->next=temp2->next;
	temp2->next=temp1;
}
int main()
{
	head=NULL;
	Insert(86,1);//List:86
	Insert(60,2);//List:86 60
	Insert(90,2);//List:86 90 60
	Print();
}

3.尾插法

void Insert(int x)
{
    struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node));
    temp1->data = x;
    temp1->next = NULL;
    if (head == NULL)
    {
        head = temp1;
        return;
    }
    struct Node* temp2 = head;
    while (temp2->next != NULL)
    {
        temp2 = temp2->next;
    }
    temp2->next = temp1;
}

二、删除

#include<stdio.h>
#include<stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};
struct Node* head;
void Print()//打印链表 
{
    struct Node* temp=head;
    printf("List is: ") ;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}
void Insert(int x)
{
    struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node));
    temp1->data = x;
    temp1->next = NULL;
    if (head == NULL)
    {
        head = temp1;
        return;
    }
    struct Node* temp2 = head;
    while (temp2->next != NULL)
    {
        temp2 = temp2->next;
    }
    temp2->next = temp1;
}


void Delete(int n)
{
	struct Node* temp1=head;
	if(n==1)
	{
		head=temp1->next;
		free(temp1);
		return;
	}
	int i;
	for(i=0;i<n-2;i++)
	{
		temp1=temp1->next;
	} 
	struct Node* temp2=temp1->next;
	temp1->next=temp2->next;
	free(temp2);
}


int main()
{
	head=NULL;
	Insert(86);//List:86
	Insert(70);//List:86 70
	Insert(90);//List:86 70 90
	Insert(88);//List:86 70 90 88
	Print();
	int n;
	printf("input a position\n");
	scanf("%d",&n);
	Delete(n);
	Print();
}

 三、反转链表

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值