当前位置:网站首页>Print linked list from end to end (6)

Print linked list from end to end (6)

2022-06-10 16:32:00 Burn slowly

// 6: Print linked list from end to end 
//  subject : Enter the head node of a linked list , Print the value of each node from the end to the end .
 
#include<iostream>
#include<stack>
using namespace std;
 
struct ListNode{
	int m_nValue;
	ListNode * m_pNext;
};
 
// Create an empty single linked list of leading nodes 
void InitList(ListNode **L)	{
	*L = (ListNode*)malloc(sizeof(ListNode));// Create a header node 
	(*L)->m_pNext = NULL;// Create an empty single linked list 
}
 
// Use stack : First in, then out ; Put each traversed node from the top of the stack to the bottom of the stack , After traversing the linked list , Output one by one from the top of the stack , Because the top of the stack comes out first , Out of stack after stack bottom .
void print_stack(ListNode * pHead){
	stack<ListNode *> nodes;
	
	ListNode * pNode = pHead;
	while (pNode != nullptr){
		nodes.push(pNode);
		pNode = pNode->m_pNext;
	}
 
	while (!nodes.empty()){
		pNode = nodes.top();
		printf("%d\n", pNode->m_nValue);
		nodes.pop();
	}
}
 
// Using recursion ( Too many layers can overflow the stack )
void print_recurve(ListNode * pHead){
	if (pHead != nullptr){
		if (pHead->m_pNext != nullptr){
			print_recurve(pHead->m_pNext);
		}
		printf("%d\n", pHead->m_nValue);
	}
}
 
// Add the single linked list of the leading node 
void add_head(ListNode * pHead,int value){
	ListNode * pNew = new ListNode();
	pNew->m_nValue = value;
	pNew->m_pNext = nullptr;
	ListNode * pNode = pHead;
	while (pNode->m_pNext != nullptr){
		pNode = pNode->m_pNext;
	}
	pNode->m_pNext = pNew;
}
 
// Add a single linked list without leading nodes 
void add_no_head(ListNode ** pHead, int value){
	ListNode * pNew = new ListNode();
	pNew->m_nValue = value;
	pNew->m_pNext = nullptr;
	if (*pHead == nullptr){
		*pHead = pNew;
	}else{
		ListNode * pNode = *pHead;
		while (pNode->m_pNext != nullptr){
			pNode = pNode->m_pNext;
		}
		pNode->m_pNext = pNew;
	}
}
 
#if 1
int main(){
	ListNode * L;
	printf("line = %d\n",__LINE__);
	InitList(&L);
	add_head(L, 1);
	add_head(L, 2);
	add_head(L, 3);
	add_head(L, 4);
	add_head(L, 5);
	add_head(L, 6);
	//print_stack(L->m_pNext);
	print_recurve(L->m_pNext);
	return 0;
}
 
#else
int main(){
	ListNode * L=nullptr;
	printf("line = %d\n",__LINE__);
	add_no_head(&L, 1);
	add_no_head(&L, 2);
	add_no_head(&L, 3);
	add_no_head(&L, 4);
	add_no_head(&L, 5);
	//print_stack(L);
	print_recurve(L);
	return 0;
}
 
#endif

原网站

版权声明
本文为[Burn slowly]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203021014137248.html

随机推荐