题目1518:反转链表-九度
来源:互联网 发布:jsp网上商城源码 编辑:程序博客网 时间:2024/05/02 18:27
题目描述:
输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)
输入:
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。
输出:
对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。
样例输入:
5
1 2 3 4 5
0
样例输出:
5 4 3 2 1
输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)
输入:
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。
输出:
对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。
样例输入:
5
1 2 3 4 5
0
样例输出:
5 4 3 2 1
NULL
推荐指数:※※
来源:http://ac.jobdu.com/problem.php?pid=1518
这一到题是链表的操作,OJ中要求实现链表的结构(不然就太。。。)。
翻转链表,是要调整指针的方向,是的尾变头,头变尾。
1.直接的想法,是再扫描链表的同时,多使用一个指针,保持在翻转每个指针的时候,指针不断裂。(明天补充)
#include<iostream>#include<stdio.h>#include<stdlib.h>using namespace std;typedef struct node{ int val; node * next;}node;int main(){ int n; while(scanf("%d",&n)!=EOF){ node *head=new node; head->next=NULL; node *pre=head; int i; for(i=0;i<n;i++){ node *no=new node; scanf("%d",&no->val); no->next=NULL; pre->next=no; pre=no; } if(head->next==NULL) printf("NULL\n"); else { node *p=head->next; node *pre=NULL; while(p!=NULL){ node *q=p->next; p->next=pre; pre=p; p=q; } head->next=pre; p=head->next; if(p!=NULL) printf("%d",p->val); while(p->next!=NULL){ p=p->next; printf(" %d",p->val); } printf("\n"); } } return 0;}
2.新建一个nhead,扫描员link,每读一个节点加入到nhead->next.。这样在读完原链表之后就实现了翻转。(如果不想破换源链表的结构,可以在读取原链表的时候才用复制节点的方法。)
#include<iostream>#include<stdio.h>#include<stdlib.h>using namespace std;typedef struct node{ int val; node * next;}node;int main(){ int n; while(scanf("%d",&n)!=EOF){ node *head=new node; head->next=NULL; node *pre=head; int i; for(i=0;i<n;i++){ node *no=new node; scanf("%d",&no->val); no->next=NULL; pre->next=no; pre=no; } if(head->next==NULL) printf("NULL\n"); else { node *nhead=new node;nhead->next=NULL; node *p=head->next; while(p!=NULL){ node *q=nhead->next; nhead->next=p; p=p->next; nhead->next->next=q; } head->next=nhead->next; p=head->next; if(p!=NULL) printf("%d",p->val); while(p->next!=NULL){ p=p->next; printf(" %d",p->val); } printf("\n"); } } return 0;}
- 题目1518:反转链表-九度
- 九度_题目1518:反转链表
- 九度OJ-题目1518:反转链表
- 【剑指Offer面试编程题】题目1518:反转链表--九度OJ
- 九度 1518 :反转链表
- 九度oj-1518-反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 题目1518:反转链表
- 九度OJ 题目1089:数字反转
- 九度OJ 题目1089:数字反转
- Sqlite的2个问题
- TOJ 1225 数据结构练习题——Huffman Coding
- C++ string 详解
- 转载 Java中类C/C++的sizeof()操作,知晓实例大小
- GBK汉字编码表
- 题目1518:反转链表-九度
- 输入输出流
- [leetcode] Longest Substring Without Repeating Characters
- Linux kernel coding style
- 博客新起步
- c#应用程序的发布
- 设计师必备的免费素材网站
- [leetcode] Add Two Numbers
- android中使用startActivityForResult()回传数据