链表的基础知识

在大一学习链表的过程中,感觉有许多没有学过的知识,这篇文章,算是我的第一篇学习笔记,可以在后续学习中回顾,有不对的情况可以提出,谢谢大家的建议。

#pragma once
#include
#include
//#include"SList.h"
typedef int SLDateType;
//void SListPrint(SListNode* phead);

定义结构体
typedef struct Node
{
    SLDateType data;
    struct Node* next;
}Node;


void PrintList(Node* phead)//打印链表
{
    Node* cur = phead;
    while (cur != NULL)
    {
        printf("%d -> ", cur->data);
        cur=cur->next;
    }
    printf("NULL\n");
}

创建节点,存储数据
Node* createNode(int data)//创建节点,存储数据
{
    //Node* head, * node, * end;//头节点,普通节点,尾节点;(过于复杂了)
    //end = head;//若为空,这头尾节点一样
    Node* newNode = (Node*)malloc(sizeof(Node));//分配地址;
    if (!newNode) {
        printf("内存分配失败\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}


//向链表末尾插入节点
void appendNode(Node** head, int data)//eg:(&head,26);
{
    Node* newNode = createNode(data);//数据放到新的节点当中
    if (*head == NULL) {
        *head = newNode;
    }
    else {
        Node* temp = *head;//地址
        while (temp->next != NULL)
        {
            temp = temp->next;
        }
        temp->next = newNode;
    }
}


//从链表中删除节点
void deleteNode(Node** head, int key)
{
    Node* temp = *head, * prev = NULL;

    //如果头节点本身就是要删除的节点
    if (temp != NULL && temp->data == key)
    {
        *head = temp->next;//改变头节点,temp只是head的拷贝
        free(temp);
        return;
    }
    //搜索要删除的节点,保持前一个节点的指针
    while (temp != NULL && temp->data != key)
    {
        prev = temp;
        temp = temp->next;//刚好存储的是要删除的节点
    }
    //如果key不在链表当中
    if (temp == NULL)return;

     //从列表中解除节点链接
    prev->next = temp->next;//刚好跳到下一个节点
    free(temp);//释放内存
}

//进行链表相关功能测试
int main()
{
    //SListNode *pnode=creat(3);
    //SListPrint(pnode);
    Node* head = NULL;
    //插入节点
    appendNode(&head, 10);
    appendNode(&head, 20);
    appendNode(&head, 30);

    //打印链表
    printf("创建链表\n");
    PrintList(head);

    //删除节点
    deleteNode(&head, 20);
    printf("删除节点\n");
    PrintList(head);

    //再次插入节点
    appendNode(&head, 40);
    printf("再次插入的节点\n");
    PrintList(head);

    return 0;
}

运行的结果

链表的基础知识_第1张图片

你可能感兴趣的:(链表,网络,数据结构)