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
- c语言--通过栈反转链表
- 反转链表-C语言实现
- 一个链表创建、反转、打印的C语言代码
- (C语言)链表的反转(一次遍历)
- C语言 链表反向打印与反转
- C语言实现双向链表的反转
- C语言实现单向链表的反转
- c语言手动实现反转链表 Reverse
- c链表反转
- 【C++】反转链表
- C语言:链表的反向输出(反转链表+栈结构)
- 反转一个邻接表C语言
- C语言反转单链表
- C语言字符串反转
- 字符串反转(C语言)
- C语言反转单链表
- C语言字符串反转
- C语言字符串反转
- windows使用的各种字符串
- JavaScript reduce用法
- 克隆二叉树
- Intellij IDEA远程向hadoop集群提交mapreduce作业
- win10中VMWare最小化安装的CentOS在NAT模式下与主机和外网相互ping通
- c语言--通过栈反转链表
- Javascipt 代码暂存
- 登录页面
- 插入排序(c实现)
- 《在macbook上修改MySQL的初始密码》
- 安卓studio打包时出现OOM: GC overhead limit exceeded
- SwiftyJSON的使用
- 翻转二叉树
- spring事务管理