데이터 구조 상의 연습 (2) 싱글 체인 시트

#include "stdafx.h"
#include "stdlib.h"
#include "malloc.h"

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2

typedef int Status;
typedef char ElemType;

typedef struct LNode{
    ElemType data;
    struct LNode *next;
}LNode,*LinkList;


void CreateList_L(LinkList &L,int n){
    LinkList p;
    int i;
    L = (LinkList)malloc(sizeof(LNode));
    L->next = NULL;
    for (i = n; i > 0;--i){
        p = (LinkList)malloc(sizeof(LNode));
        scanf_s("%d", &p->data);
        p->next = L->next;
        L->next = p;
    }
}

Status InsertList_L(LinkList L, int i, ElemType e){
    LinkList p, s;
    int j = 0;
    p = L;
    while(p && j<i-1){
        p = p->next;
        ++j;
    }
    if (!p || j>i - 1)
        return ERROR;
    s = (LinkList)malloc(sizeof(LNode));
    s->data = e;
    s->next = p->next;
    p->next = s;
    return OK;
}

Status DeleteList_L(LinkList &L, int i, ElemType &e){
    LinkList p, q;
    int j = 0;
    p = L;
    while(p->next && j<i-1){
        p = p->next;
        ++j;
    }
    if (!(p->next) || j>i - 1)
        return ERROR;
    q = p->next;
    p->next = q->next;
    e = q->data;
    free(q);
    return OK;
}

Status GetElem_L(LinkList L, int i, ElemType &e){
    LinkList p;
    int j = 1;
    p = L->next;
    while(p || j<i){
        p = p->next;
        ++j;
    }
    if (!p || j>i)
        return ERROR;
    e = p->data;
    return OK;
}

void display(LinkList L) {
    LinkList p;
    p = L->next;
    while (p){
        printf("%d", p->data);
        p = p->next;
    }
    printf("
"
); } void MergeList_L(LinkList &La, LinkList &Lb, LinkList &Lc) { LinkList pa, pb, pc; pa = La->next; pb = Lb->next; Lc = pc = La; while(pa && pb) if(pa->data <= pb->data){ pc->next = pa; pc = pa; pa = pa->next; }else{ pc->next = pb; pc = pb; pb = pb->next; } pc->next = pa ? pa : pb; free(Lb); } int main() { LinkList L; CreateList_L(L, 3); display(L); InsertList_L(L, 2, 100); display(L); ElemType e; DeleteList_L(L, 2, e); display(L); printf(" =%d
"
, e); GetElem_L(L, 3, e); printf(" =%d
"
, e); LinkList Lb,Lc; CreateList_L(Lb, 2); display(Lb); printf("
"
); MergeList_L(L, Lb, Lc); display(Lc); getchar(); getchar(); return 0; }

좋은 웹페이지 즐겨찾기