1. 程式人生 > >【DSA】雙向連結串列(程式碼)

【DSA】雙向連結串列(程式碼)

資料結構再複習。本文實現了雙向連結串列的基本操作。
【注】:本文標題DSA含義是(Data struct & algorithm)
在這裡插入圖片描述


/**
 * 雙向連結串列
 * 初始化連結串列 : A B C D E F G H I J K L M N O P Q R S T U V W X Y
 * 輸入正整數4: E F G H I J K L M N O P Q R S T U V W X Y Z A B C D
 * 輸入負整數-4:W X Y Z  A B C D E F G H I J K L M N O P Q R S T U V 
 */
#include <stdio.h>
#include <stdlib.h>

typedef char ElemType;
typedef int Status;

#define     TRUE    (1)
#define     FALSE   (0)    

typedef struct DoubleNode
{
    ElemType data;
    struct DoubleNode *pre;
    struct DoubleNode *next;

}DoubleNode, *DoubleList;


Status initList(DoubleList *list)
{
    // malloc header node
    DoubleList pHead = (DoubleList)malloc(sizeof(DoubleNode));
    DoubleNode *p, *q;

    (*list) = pHead;
    (*list)->pre = (*list)->next = NULL;
    if(!(*list))
    {
        return FALSE;
    }
    p = (*list);

    int i = 0;
    for (i = 0; i < 26; i++)
    {
        q = (DoubleNode*)malloc(sizeof(DoubleNode));
        if(!q)
        {
            return FALSE;
        }
        q->data = 'A' + i;
        q->pre = p;
        q->next = p->next;
        p->next = q;
        printf("%c ", p->data);
        p = q;
    }
    // 迴圈完畢,為節點指向頭結點的 next節點,頭結點的next節點指尾節點
    p->next = (*list)->next;
    (*list)->next->pre = p;
    printf("\n");

    return TRUE;
}

void Sort(DoubleList *list, int i)
{
    if (i > 0)
    {
        printf("i > 0\n");
        do
        {
            (*list) = (*list)->next;
        }while(--i);
    }
    if (i < 0)
    {
        i = i+26;
        printf("i < 0\n");
        do 
        {
            (*list) = (*list)->next;
        }while(--i);
    }
}

void PrintList(DoubleList *list)
{
    if(!list)
    {
        return;
    }
    int i = 0;
    for ( i = 0; i < 26; ++i)
    {
        (*list) = (*list)->next;
        printf("%c ", (*list)->data);
    }

}

int main(int argc, char const *argv[])
{

    DoubleList *list = (DoubleList*)malloc(sizeof(DoubleList));

    initList(list);

    int number;
    printf("Please input an int number: ");
    scanf("%d", &number);

    printf("number [%d]\n", number);
    Sort(list, number);

    PrintList(list);

    return 0;
}