一、插入
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();
}
三、反转链表