【鏈表】基本鏈表操作

這裏立一個flag:
1 鏈表基本操作;
2 電腦鍵盤輸入,隨機出現"[]"
3 隊列模擬鏈表
4 求鏈表的第K大的數;

完成時間:明天

一、理解題目
對鏈表進行操作,包括創建鏈表,增、刪、改、查操作,打印鏈表操作;
二、擬定方案

三、code

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

typedef struct node{
    int data;
    struct node *next;
}LNode, *LinkedList;

LinkedList headInsert(LinkedList* phead)
{
    LinkedList p, head;
    head = (LinkedList)malloc(sizeof(LNode));
    *phead = head;
    head->next = NULL;
    int num;
    scanf("%d", &num);
    while(num != -1)
    {
        p = (LinkedList)malloc(sizeof(LNode));
        p->data = num;
        p->next = head->next;
        head->next = p;
        scanf("%d", &num);
    }
    return head;
}

LinkedList tailInsert(LinkedList* phead)
{
    LinkedList p, tail;
    tail = (LinkedList)malloc(sizeof(LNode));
    *phead = tail;
    tail->next = NULL;
    int num;
    scanf("%d", &num);
    while(num != -1)
    {
        p = (LinkedList)malloc(sizeof(LNode));
        p->data = num;
        p->next = tail->next;
        tail->next = p;
        tail = p;
        scanf("%d", &num);
    }
    return *phead;
}

void addK(LinkedList L, int k, int num)
{
    int i;
    LinkedList p,s;
    p = L->next;// first node is empty, so we use the next node as the start;
    for(i = 0; i < k - 1; i++)
    {
        p = p->next;
    }
    s = (LinkedList)malloc(sizeof(LNode));
    s->data = num;
    s->next = p->next;
    p->next = s;
    return;
}
//delete the k'th node;
void deleteK(LinkedList L, int k)
{
    int i;
    LinkedList p, s;
    p = L->next;
    for(i = 0; i < k - 1; i++)
    {
        p = p->next;
    }
    s = p->next;
    p->next = s->next;
    free(s);
    return;
}

void updateK(LinkedList L, int k, int num)
{
    int i;
    LinkedList p;
    p = L->next;
    for(i = 0; i < k - 1; i++)
    {
        p = p->next;
    }
    p->data = num;
    return;
}

int getK(LinkedList L, int k)
{
    int i;
    LinkedList p = L->next;
    for(i = 0; i < k; i++)
    {
        p = p->next;
    }
    return p->data;
}

void print(LinkedList L)
{
    LinkedList p = L->next;
    while(p != NULL)
    {
        printf("data=%d\t", p->data);
        p = p->next;
    }
    printf("\n");
    return;
}

int main()
{
    LinkedList head = NULL;

    head = headInsert(&head);
    print(head);
    free(head);
    head = tailInsert(&head);
    print(head);

    addK(head, 3, 9);
    print(head);

    deleteK(head, 4);
    print(head);

    updateK(head, 3, 9);
    print(head);

    printf("%d\n", getK(head, 3));
    print(head);

    return 0;
}

四、回顧
1 如同練武入門的劈砍刺,雖是基本功,但是踏實了,就會有大作用;

參考文獻

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章