插入:
#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