C++操作单链表ListNode

C++操作单链表ListNode

通过C++进行单链表的创建、打印以及利用栈实现逆序打印。

单链表的创建和打印

#include 
using namespace std;//定义结构体
struct ListNode{int val;ListNode* next;
};class Solution
{
public:/*创建单链表*/void createList(ListNode *head){int i;ListNode* phead=head; //不破坏头指针for(i=1;i<10;i++){ListNode* node=new ListNode;node->val=i;node->next=NULL;phead->next=node;phead=node;}cout<<"链表创建成功!\n";}/*打印链表*/void printList(ListNode* head){ListNode* phead=head;while(phead!=NULL){cout<val<<" ";phead=phead->next;}cout<<"\n";}		
};int main()
{ListNode* head=new ListNode;Solution ll;head->val=0;head->next=NULL;ll.createList(head);ll.printList(head);return 0;
}

逆序打印单链表的方式

#include 
#include 
#include 
using namespace std;//定义结构体
struct ListNode{int val;ListNode* next;
};class Solution
{
public:/*创建单链表*/void createList(ListNode *head){int i;ListNode* phead=head; //不破坏头指针for(i=1;i<10;i++){ListNode* node=new ListNode;node->val=i;node->next=NULL;phead->next=node;phead=node;}cout<<"链表创建成功!\n";}/*打印链表*/void printList(ListNode* head){ListNode* phead=head;while(phead!=NULL){cout<val<<" ";phead=phead->next;}cout<<"\n";}		/*利用栈先进后出的思想*/vector printListInverseByStack(ListNode* head){vector result;stack arr;ListNode* phead=head;while(phead!=NULL){arr.push(phead->val);phead=phead->next;}while(!arr.empty()){result.push_back(arr.top());arr.pop();}return result;}void printVector(vector result){int i;for(i=0;i result;Solution ll;head->val=0;head->next=NULL;ll.createList(head);ll.printList(head);//利用栈逆序result=ll.printListInverseByStack(head); cout<<"利用栈逆序的结果为:\n";ll.printVector(result);return 0;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部