• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
不会投篮的邢
投篮三不沾
博客园    首页    新随笔    联系   管理    订阅  订阅

L2-022 重排链表 (25分)(java)

给定一个单链表 L​1​​→L​2​​→⋯→L​n−1​​→L​n​​,请编写程序将链表重新排列为 L​n​​→L​1​​→L​n−1​​→L​2​​→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。

输入格式:

每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (≤)。结点的地址是5位非负整数,NULL地址用−表示。

接下来有N行,每行格式为:

Address Data Next
 

其中Address是结点地址;Data是该结点保存的数据,为不超过1的正整数;Next是下一结点的地址。题目保证给出的链表上至少有两个结点。

输出格式:

对每个测试用例,顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。

输入样例:

00100 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
 

输出样例:

68237 6 00100
00100 1 99999
99999 5 12309
12309 2 00000
00000 4 33218
33218 3 -1



import java.util.Scanner;
import java.util.Vector;


public class Test {
	public static void main(String[] args) throws NumberFormatException, IOException {
		Scanner in = new Scanner(System.in);
		int start = in.nextInt();
		int n = in.nextInt();
		testtemp arr[] = new testtemp[100001];
		for(int i=0;i<n;i++){
			arr[in.nextInt()] = new testtemp(in.nextInt(), in.nextInt());
		}
		Vector<Integer> list = new Vector<Integer>();
		for(;arr[start].next!=-1;start=arr[start].next){
			list.add(start);
		}
		list.add(start);
	    int i=0;int j=list.size()-1;
	    while(i<=j){//用两个指针一个从前一个从后面遍历
	    	if(j==list.size()-1){
	    		System.out.printf("%05d %d ", list.get(j), arr[list.get(j)].num);
	    		j--;
	    	}else{
	    		System.out.printf("%05d\n", list.get(j));
	    		System.out.printf("%05d %d ", list.get(j), arr[list.get(j)].num);
	    		j--;
	    	}
	    	if(i<=j){
	    		System.out.printf("%05d\n", list.get(i));
	    		System.out.printf("%05d %d ", list.get(i), arr[list.get(i)].num);
	    		i++;
	    	}
	    	if(i>j){
	    		System.out.printf("-1");
	    	}
	    	
	}
	}
}
class testtemp{
	public int num;
	public int next;
	
	public testtemp(int num, int next){
		this.num = num;
		this.next = next;
	}
}

  

posted @ 2020-02-01 21:49  不会投篮的邢  阅读(620)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3