//c語言
#include<stdio.h>
#include<stdlib.h>
//鏈表的結點定義
struct node{
int data;
struct node *next;
};
//棧
struct zhan{
int data;
struct zhan *next;
};
//尾插建表,帶頭結點
struct node *create_list(){
struct node *H=(struct node *)malloc(sizeof(struct node)); //申請空間
H->next=NULL; //指空
struct node *s,*r=H; //r尾指針指空
int x;
scanf("%d",&x);
while(x!=-1){
s=(struct node *)malloc(sizeof(struct node));
s->data=x;
s->next=r->next; //s指空,同 s->next=NULL
r->next=s; //s加入鏈表中
r=s; //尾指針後移
scanf("%d",&x);
}
return H;
}
//入棧,相當於用頭插法創建鏈表,帶頭結點
struct zhan *pushstack(struct zhan *top,int x){
struct zhan *p;
p=(struct zhan *)malloc(sizeof(struct zhan));
if(p==NULL) return NULL;
p->data=x;
p->next=top->next; // p指向棧中原來的top指向結點,最初爲空
top->next=p; // top指向p,p成爲棧中的第一個有數據的節點
return top;
}
//出棧,即刪除top指向的結點(棧頂)
int popstack(struct zhan *top){
struct zhan *p;
int x;
if (top->next==NULL) return -1;
p=top->next;
x=p->data;
top->next=p->next;
free(p);
return x;
}
//打印鏈表
void print(struct zhan * H){
struct zhan *p=H;
while(p->next!=NULL){
p=p->next;
printf("%d ",p->data);
}
printf("\n");
}
void main(){
struct node *head; //定義鏈表頭結點
struct zhan *top; //定義棧頂
int x;
top=(struct zhan *)malloc(sizeof(struct zhan));
top->next=NULL;
head=create_list(); //創建結點
while(head->next!=NULL){//將鏈表壓入棧中
head=head->next;
pushstack(top,head->data);
}
while(top->next!=NULL){ //出棧
x=popstack(top);
printf("%d ",x);
}
printf("\n");
//print (top);
}
##以下是在網上答題的OJ代碼,c++,直接用的頭插法的思想反轉鏈表,該傳入的鏈表不帶頭結點
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> a;
while(head!=NULL){
a.insert(a.begin(),head->val);
head = head -> next;
}
return a;
}
};