链表相对于数组来说有诸多的优点:
- 节省内存,有效的利用空间
- 删除某一数据,在某一位置插入数据,很方便快捷
但是相对于数组来说,也是有缺点的,就是查找会慢一些。
对于链表的操作无非就是,插入、删除、查找。
typedef struct node{
int data;
struct node *next;
}Node;
创建链表
Node *create(Node *t,int n){
int i;
Node *p,*pr;
t = (Node *)malloc(sizeof(Node);
pr = t;
for(i=0;i<n;i++){
p = (Node*)malloc(sizeof(Node));
scanf("%d",&p->data);
pr->next = p;
pr = p;
}
pr->next = NULL;
return t;
}
输出(遍历)链表
void display(Node *t){
t=t->next;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
printf("\n");
}
插入数据
/*
* n:在链表的第n个位置插入
* m:所插入的数据
*/
Node *insert(int n,int m,Node *t){
Node *p = NULL,*pr = t;
p = (Node*)malloc(sizeof(Node));
p->data = m;
int i=0;
while(pr&&i<n-1){
i++;
pr = pr->next;
}
p->next = pr->next;
pr->next = p;
return t;
}
删除数据
/*n:删除第n个数据*/
Node *Delete(int i,Node *t){
int i;
Node *p = NULL,*pr = t;
while(pr&&i<n-1){
i++;
pr=pr->next;
}
p = pr->next;
pr->next = p->next;
free(p);
return t;
}
完整代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}Node;
Node* create(Node *t,int n){
Node *p,*pr;
int i;
t = (Node *)malloc(sizeof(Node));
pr = t;
for(i=0;i<n;i++){
p = (Node*)malloc(sizeof(Node));
scanf("%d",&p->data);
pr->next = p;
pr = p;
}
pr->next = NULL;
return t;
}
void display(Node *t){
t=t->next;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
printf("\n");
}
Node *insert(int n,int m,Node *t){
Node *p = NULL,*pr = t;
p = (Node*)malloc(sizeof(Node));
p->data = m;
int i=0;
while(pr&&i<n-1){
i++;
pr = pr->next;
}
p->next = pr->next;
pr->next = p;
return t;
}
Node *Delete(int n,Node *t){
int i;
Node *p = NULL,*pr = t;
while(pr&&i<n-1){
i++;
pr=pr->next;
}
p = pr->next;
pr->next = p->next;
free(p);
return t;
}
int main(){
int n,m;
Node *head = NULL;
while(scanf("%d",&n)!=-1){
head=create(head,n);
display(head);
scanf("%d%d",&n,&m);
head=insert(n,m,head);
display(head);
scanf("%d",&n);
head = Delete(n,head);
display(head);
}
return 0;
}