After several exercises of linked lists, I finally concluded a set of templates for creating linked lists and adding nodes.
1. Create a head node;
2. Create a new node;
3. Create a linked list;
4. Print the linked list;
Following these four principles to build a linked list and print it can be said that the ideas and steps are very clear!
In the last section, I had a head plug, this time I will write about the tail plug, and use these four steps to do it once!
一、创建头结点(垃圾值或者不给值)
ListNode* head = new ListNode;
head->next = NULL;
head->val = 0;
二、创建新结点,并返回一个结点类型
ListNode* creatNode(int value)
{
ListNode* newNode = new ListNode;
newNode->val = value;
newNode->next = nullptr;
return newNode;
}
三、创建链表,将头结点与新结点放在一起,并连接起来
void creatList(ListNode*pHead,int value)
{
ListNode* newNode = creatNode(value);
ListNode* tailNode = pHead;
while(tailNode->next!=NULL)
{
tailNode = tailNode->next;
}
tailNode->next = newNode;
}
四、打印链表,将头结点代入,设置一个访问指针,指向头结点的下一个结点
void printList(ListNode* pHead)
{
ListNode* q = pHead->next;
while(q)
{
cout << q->val;
q = q->next;
}
}