1. 程式人生 > >連結串列的幾個基礎操作

連結串列的幾個基礎操作

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef int ElemType;

typedef struct Node {
    ElemType data;
    struct Node *next;
}Node,*LinkedList;

LinkedList LinkedListInit() {
    Node *L;
    L = (Node *)malloc(sizeof(Node));
    if(L == NULL) {
        printf("申請記憶體空間失敗\n");
    }
    L->next = NULL;
 	return L;
}

//改為尾插法
LinkedList LinkedListCreatH() {
    Node *L, *head;
    head = (Node *)malloc(sizeof(Node));
    head->next = NULL;
    L = head;

    ElemType x;
    while(scanf("%d",&x) != EOF) {
        Node *p;
        p = (Node *)malloc(sizeof(Node));
        p->data = x;
        L->next = p;
        p->next = NULL;
        L = p;
    }
    return head;
}

//增加的查詢功能
LinkedList LinkedListFind( LinkedList L, ElemType num)
{
    Node *p = L->next;
    while(p != NULL && p->data != num) { //從第1個結點開始查詢data域為num的結點
        p = p->next;
    }
    return p;//找到後返回該結點指標,否則返回NULL
}

LinkedList LinkedListInsert(LinkedList L,int i,ElemType x) {
    Node *pre;
    pre = L;
    int tempi = 0;
    for (tempi = 1; tempi < i; tempi++) {
    	pre = pre->next;
	}
    Node *p;
    p = (Node *)malloc(sizeof(Node));
    p->data = x;
    p->next = pre->next;
    pre->next = p;

    return L;
}

LinkedList LinkedListDelete(LinkedList L,ElemType x)
{
    Node *p,*pre;
    p = L->next;
    while(p->data != x) {
        pre = p;
        p = p->next;
    }
    //加 if else 語句就可以刪除第一個資料了
    if(x==L->next->data){
        L->next = L->next->next;
    }
    else{
        pre->next = p->next;
    }
    free(p);
    return L;
}

int main() {
    LinkedList list,start;
 	printf("請輸入單鏈表的資料:");
    list = LinkedListCreatH();
    for(start = list->next; start != NULL; start = start->next) {
    	printf("%d ",start->data);
	}
    printf("\n");

    ElemType num;
    printf("請輸入你要查詢的數: ");
    scanf("%d",&num);
    if(LinkedListFind( list, num) != NULL) {
        printf("這個數存在\n");
    }
    else {
        printf("這個數不存在\n");
    }

    int i;
    ElemType x;
    printf("請輸入插入資料的位置:");
    scanf("%d",&i);
    printf("請輸入插入資料的值:");
    scanf("%d",&x);
    LinkedListInsert(list,i,x);
    for(start = list->next; start != NULL; start = start->next) {
    	printf("%d ",start->data);
	}
    printf("\n");
    printf("請輸入要刪除的元素的值:");
    scanf("%d",&x);
    LinkedListDelete(list,x);
    for(start = list->next; start != NULL; start = start->next) {
    	printf("%d ",start->data);
	}
    printf("\n");

    return 0;
}