題目:java
翻轉一個鏈表this
樣例:編碼
給出一個鏈表1->2->3->null,這個翻轉後的鏈表爲3->2->1->nullspa
編碼實現:.net
思路:先用了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 }