链表的创建(头插法尾插法)与遍历

来源:互联网 发布:如何培养英语兴趣 知乎 编辑:程序博客网 时间:2024/05/29 16:22

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

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

和head所保存的地址是一样的。


#include <iostream>#include<string>#include <vector>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 createList2(ListNode* &pHead){<span style="white-space:pre"></span>pHead=new ListNode;<span style="white-space:pre"></span>pHead->next=NULL;<span style="white-space:pre"></span>ListNode* p=new ListNode;<span style="white-space:pre"></span>p->next=NULL;<span style="white-space:pre"></span>for(int i=1;i<10;i++)<span style="white-space:pre"></span>{<span style="white-space:pre"></span> ListNode* pNewNode=new ListNode;<span style="white-space:pre"></span> pNewNode->m_key=i;<span style="white-space:pre"></span> pHead->next=pNewNode;<span style="white-space:pre"></span> pNewNode->next=p;<span style="white-space:pre"></span> p=pNewNode;<span style="white-space:pre"></span>}}void destoryList(ListNode* pHead){        ListNode* pNext = pHead->next;    while(pNext != NULL)    {        delete pHead;        pHead = pNext;        pNext = pHead->next;    }    delete pHead;    pHead = NULL;    return;}void loop(ListNode* pHead){<span style="white-space:pre"></span>//尾插法遍历 /*while(pHead->next)//这种就是链表有头结点 {  cout<<pHead->next->m_key<<" ";  pHead=pHead->next; } while(pHead)//这种就是链表没有有头结点 {  cout<<pHead->m_key<<" ";  pHead=pHead->next; }*/ //头插法遍历 ListNode * p=pHead->next; while(p->next) {  cout<<p->m_key<<" ";  p=p->next; }}int main(){    ListNode* head = NULL;    createList2(head);<span style="white-space:pre"></span>loop(head);    destoryList(head);}

0 0
原创粉丝点击