单向链表创建
2016-03-11 14:31
267 查看
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; struct link { int data; struct link *next; }; typedef struct link lb; lb *creatlink(int n) { lb *head,*p,*q; int x; head=q=(lb*)malloc(sizeof(lb)); if(head!=NULL) { head->next=NULL; for(int i=0;i<n;i++) { p=(lb*)malloc(sizeof(lb)); cin>>p->data; q->next=p; q=q->next; } } q->next=NULL; return head; } void out(lb *head) { struct link *p=head; while(p!=NULL&&p->next!=NULL) { p=p->next; cout<<p->data<<" "<<endl; } } void freelink(lb *head) { lb *p=head; lb *q=NULL; while(p!=NULL) { q=p; p=p->next; free(q); } } int main() {int n; struct link *head; while(cin>>n) { head=creatlink(n); out(head); free(head); } return 0; }
in:5
1 5 7 9 4
out:1
5
7
9
4
逆向创建
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; struct antilink { int data; struct antilink *next; }; typedef struct antilink al; al *creatlink() { al *p,*q; int x; cin>>x; while(x!=0) { p=(al*)malloc(sizeof(al)); p->data=x; p->next=q; q=p; cin>>x; } return q; } void out(al*head) { al *p=head; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } } void freelist(al*head) { al *p=head; al *q=NULL; while(p!=NULL) { q=p; p=p->next; free(q); } } int main() {al *head; head=creatlink(); out(head); freelist(head); return 0; }
in:1 2 3 4 5
out:5 4 3 2 1
相关文章推荐
- 开启Mysql远程访问权限
- I/O重定向的原理和实现
- 求解n皇后
- 100个精彩的开源游戏
- JRE/JDK/JVM之间关系
- iOS开发工具——网络封包分析工具Charles
- MySQL show status参数详解
- Android 学习资料收集
- [C]为什么发明指针?
- linux复制粘贴部分字符
- 搞懂php apache mysql tomcat
- 详析手游圈从业人员必须知道的行业术语
- js window的使用
- Eclipse复制当前行问题(Intel屏幕旋转冲突)
- nginx http2配置
- c++第1次实验-3
- (转载)Setup Factory 会话变量
- 搜索引擎选择: Elasticsearch与Solr
- 多层感知器 - Multilayer Perceptron --(Back-propagation Algorithm - 反馈神经网络)
- ObjectOutputStream在文件末尾多次追加写入对象的解决方案