CodeHighlight

2013年10月5日 星期六

[DS]Link list 實作 by C

這次是Link List的練習,新增node的部分是用stack的概念,
本身是單向的list,刪除是針對特定Data做刪除,
Reverse的部分稍微卡了一下,那三個指標的平移不熟悉的話,回傳的指標是指向神秘的未知空間呀!


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

typedef struct node{
        int data;
        struct node *link;
}NODE;


NODE* addNode(NODE* head, int addData){
        NODE *newNode;
        newNode = (NODE*)malloc(sizeof(NODE));
        newNode->data = addData;
        newNode->link = head;
        head = newNode;
        return head;
}

NODE* delNode(NODE* head, int delData){
        NODE *preNode = NULL;
        NODE *firstNode = head;
        NODE *tmpNode;
        if(head == NULL){
                printf("EMPTY LIST\n");
                return;
        }
        while(head != NULL){    //Find Each Node
                if(head->data == delData){
                        tmpNode = head;
                        if(preNode != NULL){
                                preNode->link = head->link;
                        }
                        else{//List Head
                                firstNode = head->link;
                        }
                        free(tmpNode);
                }
                else{
                        preNode = head;
                        head = head->link;
                }
        }
        return firstNode;
}

NODE* reverseList(NODE *head){
        NODE *p,*t,*r;
        p = NULL;
        t = head;
        r = head->link;
        while(t != NULL){
                r = t->link;
                t->link = p;
                p = t;
                t = r;
        }
        return p;
}

void showAllList(NODE* head){
        if(head == NULL){
                printf("EMPTY LIST\n");
                return;
        }
        while(head != NULL){
                printf("%d->", head->data);
                head = head->link;
        }
        printf("\n");
}

int main(){
        NODE *head;
        head = addNode(head, 1);
        head = addNode(head, 2);
        head = addNode(head, 3);
        head = addNode(head, 4);
        head = addNode(head, 5);
        head = addNode(head, 6);
        head = addNode(head, 7);
        head = addNode(head, 8);
        head = addNode(head, 1);
        head = addNode(head, 2);
        head = addNode(head, 3);
        head = addNode(head, 4);
        head = addNode(head, 5);
        head = addNode(head, 6);
        head = addNode(head, 7);
        head = addNode(head, 8);

        showAllList(head);
        head = reverseList(head);
        showAllList(head);
        head = delNode(head, 2);
        showAllList(head);
        return 0;
}