头部插入
#include<iostream>
struct ListNode{
int m_nValue;
ListNode* m_pNext;
};
void AddToTop(ListNode** pHead, int Value)
{
ListNode* pNew = new ListNode();
pNew->m_nValue = Value;
pNew->m_pNext = nullptr;
if(*pHead == nullptr){
*pHead = pNew;}
else{
pNew->m_pNext = *pHead;
*pHead = pNew;}
}
void print(ListNode* pHead){
printf("LinkedList is:\n");
while(pHead!=nullptr)
{
printf("%d ",pHead->m_nValue);
pHead = pHead->m_pNext;
}
printf("\n");
}
int main(){
ListNode* pHead = nullptr;
AddToTop(&pHead, 1);
AddToTop(&pHead, 2);
AddToTop(&pHead, 3);
AddToTop(&pHead, 4);
print(pHead);
}
运行输出: