学习笔记 单链表的基本操作
经过这次上手打出单链表后 感觉完全掌握单链表, 增删查改样样俱全 无头插法 太过简单
#include<stdlib.h>
#include<stdio.h>
typedef int ElementType;
int MaxSize;
typedef struct Node{
int data;
struct Node* next;
}Node,*List,*Position;
void initializer_list(List L){
L = (List)malloc(sizeof(Node));
if(!L)
exit(0);
L->next = NULL;
}
List TailInsert(List L){
int x;
Node *P, *r;
L = (Node *)malloc(sizeof(Node));
L->next == NULL;
r = L;
printf("请输入你的链表长度:");
scanf("%d",&MaxSize);
for(int i = 1;i <= MaxSize;i++){
P = (Node *)malloc(sizeof(Node));
if(P == NULL){
printf("Out of space!");
exit(0);
}else{
printf("请输入你的第%d个结点的数据:",i);
scanf("%d",&x);
P->data = x;
r->next = P;
r = P;
}
}
r->next = NULL;
printList(L);
return L;
}
List Insert(List L,int Pos,ElementType X){
Node* P = L;
Position TempCell = malloc(sizeof(struct Node));
if(TempCell == NULL){
printf("Out of space!");
exit(0);
}else{
for(int i = 1;i < Pos;i++){
P = P->next;
}
TempCell->data = X;
TempCell->next = P->next;
P->next = TempCell;
MaxSize++;
}
printList(L);
return L;
}
void printList(List L){
List q;
q = L->next;
while(q){
printf("%d ",q->data);
q = q->next;
}
printf("\n");
}
int Lenth(List L){
int Lenth = 0;
Node *P = L->next;
while(P){
P = P->next;
Lenth++;
}
return Lenth;
}
List PreNode(List L,int Pos){
Node *r = L;
for(int i = 1; i < Pos; i++){
r = r->next;
}
return r;
}
List Delete_Position(List L){
int Pos;
printf("请输入你要删除的结点的位置:");
scanf("%d",&Pos);
if(Pos > MaxSize){
printf("you little bitch,you'r out of MaxSize.\n");
}else
{
List P;
List r = L->next;
for(int i = 1; i < Pos; i++){
r = r->next;
}
P = PreNode(L, Pos);
P->next = r->next;
free(r);
}
printList(L);
return L;
}
List Delete_data(List L){
int X,Pos = 0;
Position P;
Node *r = L;
printf("请输入你要删除的数据:");
scanf("%d",&X);
while(Pos <= MaxSize){
r = r->next;
Pos++;
if(r->data == X){
P = PreNode(L,Pos);
P->next = r->next;
free(r);
}
}
printList(L);
return L;
}
int main(){
int lenth;
List L;
L = TailInsert(L);
lenth = Lenth(L);
printf("你的链表长度为:");
printf("%d\n",lenth);
L = Insert(L,3,3);
L = Delete_data(L);
L = Delete_Position(L);
return 0;
}
|