创建单链表

创建单链表的代码很简单,需要注意的一点是,一开始首先创建一个Node,然后让pPre指向它,并在之后的每次循环中用pCurr进行创建Node(pPre的意义是要将链表连起来)。

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

struct LinkedListNode{
    int value;
    LinkedListNode *pNext;
    LinkedListNode(int v) : value(v) {}
};

LinkedListNode *CreateLinkedList(int arr[], int len)
{
    LinkedListNode *pHead = new LinkedListNode(arr[0]);
    LinkedListNode *pPre = pHead;
    LinkedListNode *pCurr = NULL;

    //每次进入该循环的时候,pPre是起作用的
    //pCurr都会重新构造一个LinkedListNode
    for (int i = 1; i < len; i++)
    {
        pCurr = new LinkedListNode(arr[i]);
        pCurr->pNext = NULL;
        pPre->pNext = pCurr;
        pPre = pCurr;
    }
    return pHead;
}

int main()
{
    int arr[10] = {4, 2, 5, 7, 4, 1, 7, 3, 1, 9};
    LinkedListNode *pHead = CreateLinkedList(arr, 10);
    while (pHead)
    {
        cout<<pHead->value<<endl;
        pHead = pHead->pNext;
    }
    return 0;
}

EOF

原文地址:https://www.cnblogs.com/lihaozy/p/2811564.html