• 【剑指offer】单链表尾部插入一个节点


    #include <iostream>
    using namespace std;
    
    //链表结构体
    struct ListNode
    {
    	int m_Value;
    	ListNode *next;
    };
    
    //创建一个单链表
    ListNode *CreateList(int *a,int n)
    {
    	ListNode *pHead = NULL;
    	ListNode *pTemp = NULL;
    	int i = 0;
    	for(i = 0; i < n; i++)
    	{
    		//ListNode *pNew = (ListNode *)malloc(sizeof(struct ListNode));
    		ListNode *pNew = new ListNode(); //创建一个新的节点
    		pNew->m_Value = a[i];
    		pNew->next = NULL;
    
    		if(NULL == pHead)
    		{
    			pHead = pNew;
    			pTemp = pNew;
    		}
    		else
    		{
    			pTemp->next = pNew;
    			pTemp = pTemp->next;
    		}
    	}
    	return pHead;
    }
    
    //链表尾部插入一个节点
    void AddTailNode(ListNode **pHead,int key)
    {
    
    	// ListNode *pNew = (ListNode *)malloc(sizeof(struct ListNode));
    	ListNode *pNew = new ListNode();
    	pNew->m_Value = key;
    	pNew->next = NULL;
    
    	/*if(NULL == pHead)
    	{
    		return;
    	}*/
    	if(NULL == *pHead)
    	{
    		*pHead = pNew;
    		return;
    	}
    	
    	ListNode *p = *pHead;
    	ListNode *q = NULL;
    	while(NULL != p)
    	{
    		q = p;
    		p = p->next;
    	}
    	q->next = pNew;
    	
    }
    int main(void)  
    {  
    	int a[5] = {3,6,8,2,1};
    	ListNode *p = CreateList(a,5);
    	//ListNode *p = NULL;
    	AddTailNode(&p,4);
    	while(NULL != p)
    	{
    		cout<<p->m_Value;
    		p = p->next;
    	}
    	return 0;  
    }    
    

      

  • 相关阅读:
    C++中的结构体
    C++转换
    C++常见问题解答
    hdu 1491
    hdu 1253
    [恢]hdu 2529
    [恢]hdu 2539
    hdu 1708
    [恢]hdu 2512
    [恢]hdu 2401
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8024441.html
Copyright © 2020-2023  润新知