c语言--通过栈反转链表

来源:互联网 发布:券老大淘宝优惠券 编辑:程序博客网 时间:2024/05/17 03:32

//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=NULLr->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;    }};











0 0
原创粉丝点击