LintCode-翻转链表

题目:

翻转一个链表

 

样例:

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

 

编码实现:

思路:先用了ArrayList按照原先的顺存起来,然后倒叙遍历将指针翻转,其他实现方式没想到暂时

 1 package com.exercise.net;
 2 
 3 import java.util.ArrayList;
 4 
 5 class ListNode{
 6     public int val ;
 7     public ListNode next ;
 8     public ListNode(int val){
 9         this.val = val ;
10         next = null ;
11     }
12     
13     public String toString(){
14         return "val="+val+"-->"+(next==null? "" : next.val);
15     }
16 }
17 
18 public class Solution {
19 
20     /**
21      * @param args
22      */
23     public static void main(String[] args) {
24         // TODO Auto-generated method stub
25         ListNode n = new ListNode(1);
26         ListNode n2 = new ListNode(2);
27         ListNode n3 = new ListNode(3);
28         ListNode n4 = new ListNode(4);
29         ListNode n5 = new ListNode(5);
30         n.next = n2; n2.next = n3; n3.next = n4 ;n4.next = n5;
31         
32         ListNode head = n ;
33         ArrayList<ListNode> list = new ArrayList<ListNode>();
34         while(head.next!=null){
35             list.add(head);
36             head = head.next; //按原始顺序装入list
37         }
38         list.add(head); //记得将最后一个也装入List
39         
40         
41         for(int i=list.size()-1;i>0;i--){ //倒叙遍历list,并修改指针next
42             list.get(i).next = list.get(i-1);
43             list.get(i-1).next = null ; //断开原始的指针链
44         }
45         
46         //校验打印
47         /*while(head.next!=null){
48             System.out.print(head.val+"\t");
49             head = head.next;
50         }
51         System.out.print(head.val);*/
52     }
53 }

 

 

 

 

 

 

posted @ 2017-08-30 15:27  穷苦书生  阅读(210)  评论(0编辑  收藏  举报