zoukankan      html  css  js  c++  java
  • 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+"	");
    49             head = head.next;
    50         }
    51         System.out.print(head.val);*/
    52     }
    53 }
  • 相关阅读:
    php程序员面试经验
    模板引擎(smarty)知识点总结五
    模板引擎(smarty)知识点总结三
    js计算字数
    phpexcel导出成绩表
    phpexcel用法(转)
    模板引擎(smarty)知识点总结
    apache泛域名解析
    对象的解构赋值
    解构赋值
  • 原文地址:https://www.cnblogs.com/crazytrip/p/7453336.html
Copyright © 2011-2022 走看看