Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Created July 11, 2013 10:42
Show Gist options
  • Save luoxiaoxun/5974450 to your computer and use it in GitHub Desktop.
Save luoxiaoxun/5974450 to your computer and use it in GitHub Desktop.
题目描述: 输入一个链表,从尾到头打印链表每个节点的值。 输入: 每个输入文件仅包含一组测试样例。 每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。 输出: 对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。 样例输入: 1 2 3 4 5 -1 样例输出: 5 4 3 2 1
#include<cstdio>
#include<stack>
using namespace std;
struct ListNode{
int val;
ListNode *next;
};
void addToTail(ListNode **head,ListNode **cur,int value){
ListNode *temp=new ListNode();
temp->val=value;
temp->next=NULL;
if(*head==NULL) *head=*cur=temp;
else{
(*cur)->next=temp;
*cur=temp;
}
}
void printListReverselyStack(ListNode *head){
stack<ListNode *>s;
ListNode *cur=head;
while(cur!=NULL){
s.push(cur);
cur=cur->next;
}
while(!s.empty()){
cur=s.top();
printf("%d\n",cur->val);
s.pop();
}
}
void printListReverselyRecursive(ListNode *head){
if(head!=NULL){
if(head->next!=NULL)
printListReverselyRecursive(head->next);
printf("%d\n",head->val);
}
}
int main(){
ListNode *head=NULL;
ListNode *cur=NULL;
int value;
while(scanf("%d",&value)!=EOF){
if(value==-1) break;
addToTail(&head,&cur,value);
}
//printListReverselyStack(head);
printListReverselyRecursive(head);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment