首页 > 其他分享 >从零构建链表

从零构建链表

时间:2022-08-30 21:59:14浏览次数:87  
标签:Node Head cout temp int next 链表 构建

最重要的头节点是这样创建的:

        Node* Head=new Node; //头节点 不存储数据

        Head->next = NULL;

        Node* pre = Head; //指向下一个节点的过渡值,本质就是保留住head这个虚拟头节点,不丢失它

   

#include<iostream>

using namespace std;

   

struct Node {

        int val;

        Node* next;

};

   

//创建

Node* creatlist(int n) {

        Node* Head=new Node; //头节点 不存储数据

        Head->next = NULL;

        Node* pre = Head; //指向下一个节点的过渡值

          

   

        cout << "请依次输入" << n << "个链表的值:";

        for (int i = 0;i < n;i++) {

                Node* temp = new Node;

                cin >> temp->val;

   

                pre->next = temp;

                pre = temp;

                temp->next = NULL;        

        }

        return Head;

}

   

//显示

void display(Node* head) {

        Node* temp=head->next;

        int e;

        cout << "该链表的遍历依次为:";

        while (temp!=NULL) {

                e = temp->val;

                cout << e << " ";

                temp = temp->next;

        }

        cout << "\n";

}

   

int main() {

        int nums;

        cout << "请输入链表的长度:";

        cin >> nums;

        Node* head = creatlist(nums);

        display(head);

        return 0;

}

  

https://blog.csdn.net/jindaxiaoooo/article/details/108937193

标签:Node,Head,cout,temp,int,next,链表,构建
From: https://www.cnblogs.com/libxing/p/16640979.html

相关文章