데이터 구조 - 이중 순환 링크 일부 기능 의 C 언어 구현

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

typedef struct Node{
    int data;
    Node *next;
    Node *last;
}Node,*PNode;//   

typedef struct List{
    PNode head;
    PNode tail;
    int length;
}List,*PList;//  

void initList(PList x){
    PNode headNode=(PNode)malloc(sizeof(Node));
    if(!headNode)
        exit(0);
    headNode->data=0;
    headNode->next=headNode;
    x->head=headNode;
    x->tail=headNode;
    x->length=0;
}//      

int insertNode(PList x,int i,int e){
    if(i>x->length)
        return 1;

    PNode newNode=(PNode)malloc(sizeof(Node));
    if(!newNode)
        exit(0);
    newNode->data=e;

    PNode p=x->head;
    for(int j=0;j<i;j++)
        p=p->next;

    newNode->next=p->next;
    p->next=newNode;
    newNode->last=p;
    newNode->next->last=newNode;

    if(i==x->length)
        x->tail=newNode;

    x->length++;

    return 0;
}//     

int deleteNode(PList x,int i){
    if(i>x->length)
        return 1;

    PNode p=x->head;
    for(int j=0;j<i-1;j++)
        p=p->next;

    PNode delNode=p->next;
    p->next=delNode->next;
    p->next->last=p;

    if(i==x->length)
        x->tail=p;

    free(delNode);
    x->length--;

    return 0;
}//     

void outputList(PList x,int h_t=0){
    if(h_t==0){
        PNode p=x->head->next;
        for(int i=0;i<x->length;i++){
            printf("%3d",p->data);
            p=p->next;
        }
        printf("
"
); } else{ PNode p=x->tail; for(int i=0;i<x->length;i++){ printf("%3d",p->data); p=p->last; } printf("
"
); } }// , , int deleteList(PList x){ while(x->length>0){ deleteNode(x,x->length); x->length--; } free(x->head); x->head=NULL; x->tail=NULL; }// int main(){ // PList myList=(PList)malloc(sizeof(List)); initList(myList); // int e=0; printf(" (10 ):"); for(int i=0;i<10;i++){ scanf("%d",&e); insertNode(myList,myList->length,e); } outputList(myList,1); // deleteList(myList); return 0; }

좋은 웹페이지 즐겨찾기