【C++】链表倒序输出
使用尽量简单的代码实现链表的倒序输出,这个就是考察使用栈的巧妙之处了。#include <iostream>using namespace std;
struct Node
{
int key;
Node* next;
};
Node* createList(int arr[],int nLength);
void printList(Node* head);
void reversePrint(Node* head);
void clearList(Node* head);
void main()
{
int arr[] = {1,3,5,7,9};
int nLength = sizeof(arr)/sizeof(arr);
Node* head = createList(arr,nLength);
printList(head);
reversePrint(head);
clearList(head);
}
Node* createList(int arr[],int nLength)
{
Node* head = new Node;
head->key = arr;
head->next = NULL;
Node *p = head;
for(int i=1;i<nLength;i++)
{
Node* ptr = new Node;
ptr->key = arr;
ptr->next = NULL;
p->next = ptr;
p = p->next;
}
return head;
}
void printList(Node* head)
{
Node* p = head;
while( p!= NULL )
{
cout<<p->key<<endl;
p=p->next;
}
}
void clearList(Node* head)
{
Node* p = head;
Node* ptr;
while( p!= NULL )
{
ptr = p->next;
delete p;
p = ptr;
}
}
void reversePrint(Node* head)
{
if( head != NULL )
{
if( head->next != NULL )
reversePrint(head->next);
}
cout<<head->key<<endl;
} 专业一点叫递归 #在这里快速回复#新人学习一下 支持 !!
页:
[1]