소 백의 데이터 구조 코드 실전 (1) - 단일 체인 표 각종 작업 의 실현

//Author:   
#include 
#include 
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
"); L->next=NULL; return L; } LinkedList create_head() { Node *L; L=init(); ElemType x; while(scanf("%d",&x)) { if(x==0) break; Node *p; p=(Node *)malloc(sizeof(Node)); p->data=x; p->next=L->next; L->next=p; } return L; } LinkedList create_tail() { 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=NULL; return L; } LinkedList clear(LinkedList L) { Node *p,*q; p=L->next; while(p!=NULL) { q=p->next; free(p); p=q; } L->next=NULL; return L; } LinkedList insert(LinkedList L,int i,ElemType x) { Node *p; p=L; int j; for(j=1;jnext; Node *q; q=(Node *)malloc(sizeof(Node)); q->data=x; q->next=p->next; p->next=q; return L; } LinkedList deletepos(LinkedList L,int i) { Node *p; p=L; int j; for(j=1;jnext; p->next=p->next->next; return L; } LinkedList deleteelem(LinkedList L,ElemType x) { Node *p,*q; p=L; while(p!=NULL) { if(p->data!=x) { q=p; p=p->next; } else { q->next=p->next; free(p); p=q->next; } } return L; } void show(LinkedList L) { Node *p; p=L->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } printf("
"); } int main() { int i,j; LinkedList L; while(1) { printf("----@@@menu@@@----
"); printf("1.
"); printf("2.
"); printf("3.
"); printf("4.
"); printf("5.
"); printf("6.
"); printf("7.
"); printf(" 1-7:"); scanf("%d",&i); switch(i) { case 1: { L=create_head(); break; } case 2: { L=create_tail(); break; } case 3: { L=clear(L); break; } case 4: { printf(" , :"); scanf("%d %d",&i,&j); L=insert(L,i,j); break; } case 5: { printf(" :"); scanf("%d",&i); L=deletepos(L,i); break; } case 6: { printf(" :"); scanf("%d",&i); L=deleteelem(L,i); break; } case 7: { show(L); break; } } } }

좋은 웹페이지 즐겨찾기