鏈表的基本使用


前言

鏈表有些時候還是很好用的(我也不知道啥時候),正好有時間穩固一下基本知識。

定義:

鏈表的基本格式是一個結構體,結構體內部有數據成員和結構體指針,結構體指針用於指向下一個節點的地址,數據成員用於存儲數據,結構如下:

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\n",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\n",head -> data);
        head = head -> next;
    }
}

int main() {
    Node *head = CreateList();
    ReadList(head);
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM