zoukankan      html  css  js  c++  java
  • 链表的基本使用

    前言

    链表有些时候还是很好用的(我也不知道啥时候),正好有时间稳固一下基本知识。

    定义:

    链表的基本格式是一个结构体,结构体内部有数据成员和结构体指针,结构体指针用于指向下一个节点的地址,数据成员用于存储数据,结构如下:

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

    创建:

    创建链表即将一个个的节点串连起来,即一个节点的指针指向下个节点地址。

    创建时需要定义三个结构体指针,一个是链表的指针,一个是头节点指针(标志),用来进行链表的访问 ,还需要有一个临时的节点指

    针,不能直接在原链表上直接进行创建,因为创建的指针不赋为空会指向非法地址,即野指针,具体操作:

    Node *CreateList() {
        Node *L, *head, *tmp;
        int num;
        L = (Node *)malloc(sizeof(Node));
        L -> next = NULL;
        head = L;
        while(scanf("%d", &num) && num) {
            tmp = (Node *)malloc(sizeof(Node) );
            tmp -> data = num;
            tmp -> next = NULL;
            L -> next = tmp;
            L = tmp;
        }
        return head;
    }

    读取:

    对原链表进行读取操作,通过上一步的创建函数可以得到一个链表的头节点地址,这个头节点并没有任何信息,只存储了第一个节点的地址,所以我们需要从头节点的下一个

    节点进行读取信息。

    代码:

    void ReadList(Node *head) {
        head = head -> next;
        while(head != NULL) {
            printf("%d
    ",head -> data);
            head = head -> next;
        }
    }

    大功告成!

    这时你应该对链表有了一个初步认识

    附完整代码:

    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <iostream>
    #include <queue>
    #include <map>
    #include <list>
    #include <utility>
    #include <set>
    #include <algorithm>
    #include <deque>
    #include <vector>
    #define mem(arr,num) memset(arr,0,sizeof(arr))
    #define _for(i, a, b) for(int i = a; i <= b; i++)
    #define __for(i, a, b) for(int i = a; i >=b; i--)
    #define IO ios::sync_with_stdio(false);
            cin.tie(0);
            cout.tie(0);
    using namespace std;
    typedef long long ll;
    typedef vector<int > vi;
    
    typedef struct node {
        int data;
        struct node *next;
    }Node;
    
    Node *CreateList() {
        Node *L, *head, *tmp;
        int num;
        L = (Node *)malloc(sizeof(Node));
        L -> next = NULL;
        head = L;
        while(scanf("%d", &num) && num) {
            tmp = (Node *)malloc(sizeof(Node) );
            tmp -> data = num;
            tmp -> next = NULL;
            L -> next = tmp;
            L = tmp;
        }
        return head;
    }
    
    void ReadList(Node *head) {
        head = head -> next;
        while(head != NULL) {
            printf("%d
    ",head -> data);
            head = head -> next;
        }
    }
    
    int main() {
        Node *head = CreateList();
        ReadList(head);
        return 0;
    }
    宝剑锋从磨砺出 梅花香自苦寒来
  • 相关阅读:
    关于分区索引对齐
    SQLSERVER 分区表实战
    鱼骨图实践
    Python之路-python(面向对象一)
    Python之路-python(常用模块学习)
    Python之路-python(装饰器、生成器、迭代器、Json & pickle 数据序列化、软件目录结构规范)
    Python之路-python(set集合、文本操作、字符编码 )
    Python之路-python数据类型(列表、字典、字符串、元祖)操作
    Python之路-python环境安装和简单的语法使用
    javascript中with语句应用
  • 原文地址:https://www.cnblogs.com/GHzcx/p/9196891.html
Copyright © 2011-2022 走看看