วันศุกร์ที่ 10 ธันวาคม พ.ศ. 2553

Exersice 3 - cs621

การเขียน โปรแกรมสร้าง Link List ด้วยภาษา C

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

struct node
{
            int data;
            struct node *next;
};

/*การเพิ่ม โหนดใน Linked List*/

struct node* add(struct node *head, int data)
{
            struct node *tmp;

            if(head == NULL)
{
                        head=(struct node *)malloc(sizeof(struct node));
                        if(head == NULL)
{
                                    printf("Error! memory is not available\n");
                                    exit(0);
                        }
                        head-> data = data;
                        head-> next = head;
                        }
else
{
                        tmp = head;
                        while (tmp-> next != head)
                                    tmp = tmp-> next;
                        tmp-> next = (struct node *)malloc(sizeof(struct node));
                        if(tmp -> next == NULL)
                        {
                                    printf("Error! memory is not available\n");
                                    exit(0);
                        }
                        tmp = tmp-> next;
                        tmp-> data = data;
                        tmp-> next = head;
            }
            return head;
}

/*สร้าง Function สำหรับprint ค่า*/

void printlist(struct node *head)
{
            struct node *current;
            current = head;
            if(current!= NULL)
            {
                        do
                        {
                                    printf("%d\t",current->data);
                                    current = current->next;
                        }
while (current!= head);
                        printf("\n");
            }
            else
                        printf("The list is empty\n");

}

/*การลบ โหนดใน Linked List*/

void destroy(struct node *head)
{
            struct node *current, *tmp;
            current = head->next;
            head->next = NULL;
            while(current != NULL)
{
                        tmp = current->next;
                        free(current);
                        current = tmp;
            }
}


/*ทำการเพิ่มโหนดใน Linked List และเรียกใช้ Function printlist เพื่อแสดงค่าที่อยู่ใน Linked List*/

void main()
{
            struct node *head = NULL;
            head = add(head,1);
            printlist(head);

            head = add(head,20);
            printlist(head);

            head = add(head,10);
            printlist(head);
            head = add(head,5);
            printlist(head);
           
            destroy(head);
            getchar();
            return (head);
}

 ----------------------------------------------------

ไม่มีความคิดเห็น:

แสดงความคิดเห็น