小白的資料結構程式碼實戰(2)----雙向連結串列的各種操作
阿新 • • 發佈:2018-12-14
//Author:張佳琪 #include <stdio.h> #include <stdlib.h> typedef int ElemType; typedef struct Node { ElemType data; struct Node *next; }Node,*LinkedList; LinkedList init() { Node *L; L=(Node *)malloc(sizeof(Node)); if(L==NULL) printf("fail\n"); L->next=L; return L; } LinkedList create() { Node *L; L=init(); Node *r; r=L; ElemType x; while(scanf("%d",&x)) { if(x==0) break; Node *p; p=(Node *)malloc(sizeof(Node)); p->data=x; r->next=p; r=p; } r->next=L; return L; } LinkedList insert(LinkedList L,int i,ElemType x) { Node *p; p=L; int j; for(j=1;j<i;j++) p=p->next; Node *q; q=(Node *)malloc(sizeof(Node)); q->data=x; q->next=p->next; p->next=q; return L; } LinkedList deleteelem(LinkedList L,ElemType x) { Node *p,*q; p=L; while(1) { if(p->data!=x&&p->next!=L) { q=p; p=p->next; } else if(p->data!=x&&p->next==L) { break; } else if(p->data==x&&p->next!=L) { q->next=p->next; free(p); p=q->next; } else if(p->data==x&&p->next==L) { q->next=L; free(p); break; } } return L; } LinkedList deletepos(LinkedList L,int i) { Node *p; p=L; int j; if(i!=1) { for(j=1;j<i;j++) p=p->next; p->next=p->next->next; } else { while(p->next!=L) { p=p->next; } L=p->next->next; p->next=L; } return L; } void show(LinkedList L) { Node *p; p=L->next; while(1) { printf("%d ",p->data); if(p->next==L) break; p=p->next; } printf("\n"); } int main() { LinkedList L; int i,j; while(1) { printf("
[email protected]@@[email protected]@@----\n"); printf("1.建立\n"); printf("2.在某位置插入\n"); printf("3.在某位置刪除\n"); printf("4.刪除特定值\n"); printf("5.輸出\n"); printf("輸入1-5:"); scanf("%d",&i); switch(i) { case 1: { L=create(); break; } case 2: { printf("在哪裡插入,插入啥:"); scanf("%d %d",&i,&j); L=insert(L,i,j); break; } case 3: { printf("刪除哪個位置:"); scanf("%d",&i); L=deletepos(L,i); break; } case 4: { printf("刪除特定值:"); scanf("%d",&i); L=deleteelem(L,i); break; } case 5: { show(L); break; } } }