C++实现链表的创建

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

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

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

void CreateList(node* &L, int *Number,int length)
{
	L = new node;
	L->elem = Number[0];
	L->next = NULL;
	node *p=L;

	for (int i = 1; i < length; i++)
	{
		node *newNode = (node *)malloc(sizeof(node));
		newNode->elem = Number[i];
		newNode->next = NULL;
		p->next = newNode;
		p = newNode;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int A[6] = { 5, 10, 20, 15, 25, 30 };
	int B[4] = { 5, 15, 35, 25 }; 
	node *LA = NULL;
	node *LB=NULL;

	CreateList(LA, A, 6);


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);
}

两个方法效果一样。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值