zoukankan      html  css  js  c++  java
  • C++建立链表

    自己保存一下,建立链表的程序,省的以后每次建立链表的时候,还需要重新在写。

    通过下面的代码,建立的链表节点数为10,每个节点保存的数为其下标即:0-9

    这里要注意一点,在void createList(ListNode* &pHead)的时候,用的是指针引用,因为在main中head并没有开辟空间,如果在createList中为pHead开辟空间的时候,main中的head依旧还是指向NULL的。

    如果在main中为head开辟了空间的话,就不需要用指针的引用了。道理很简单,就和你传int参数是一个道理。createList中的pHead是形参,也就是说pHead的地址和main中head的地址是不一样的,如果在main中为head开辟了空间的话,那么pHead

    和head所保存的地址是一样的。后面就用了第二种方法实现。

    #include "stdafx.h"
    #include <iostream>
    #include<cstring>
    #include <vector>
    #include <assert.h>
    using namespace std;
    
    struct ListNode
    {
        int m_key;
        ListNode* next;
    };
    
    
    void createList(ListNode* &pHead)
    {
        pHead = new ListNode;
        pHead->m_key= 0;
        pHead->next = NULL;
        ListNode* p = pHead;
        for(int i=1; i<10; i++)
        {
            ListNode* pNewNode = new ListNode;
            pNewNode->m_key = i;
            pNewNode->next = NULL;
            p->next = pNewNode;
            p = pNewNode;
        }
    }
    
    void destoryList(ListNode* pHead)
    {
        assert(pHead!=NULL);
        ListNode* pNext = pHead->next;
        while(pNext != NULL)
        {
            delete pHead;
            pHead = pNext;
            pNext = pHead->next;
        }
        delete pHead;
        pHead = NULL;
        return;
    }
    
    
    int main()
    {
        ListNode* head = NULL;
        createList(head);
    
    
        destoryList(head);
    }

    void createList1(ListNode* pHead)
    {
        ListNode* p = pHead;
        for(int i=1; i<10; i++)
        {
            ListNode* pNewNode = new ListNode;
            pNewNode->m_key = i;
            pNewNode->next = NULL;
            p->next = pNewNode;
            p = pNewNode;
        }
    }
    
    
    void destoryList(ListNode* pHead)
    {
        assert(pHead!=NULL);
        ListNode* pNext = pHead->next;
        while(pNext != NULL)
        {
            delete pHead;
            pHead = pNext;
            pNext = pHead->next;
        }
        delete pHead;
        pHead = NULL;
        return;
    }
    
    
    int main()
    {
        ListNode* head = NULL;
        //createList(head);
        head = new ListNode;
        head->m_key =0;
        head->next = NULL;
        createList1(head);
    
    
        destoryList(head);
    }

    两者的效果是一样的。

  • 相关阅读:
    React使用iconfont图标下载到本地symbol引用
    【汇编】求100以内的素数asm
    jQuery Ajax.BeginForm方法回调函数高版本3.3.1不兼容问题
    python中的深拷贝与浅拷贝
    闲来无事做个C#小项目——2
    C#使用MD5加密
    数据结构部分总结(c语言版)
    vue 上传视频和图片 并且截取视频第一帧作为播放前默认图片
    vue el-cascader取id和lable的值
    C# 枚举的定义,枚举的用法,获取枚举值
  • 原文地址:https://www.cnblogs.com/cyttina/p/2740372.html
Copyright © 2011-2022 走看看