zoukankan      html  css  js  c++  java
  • 反转链表

    题目描述

    输入一个链表,反转链表后,输出新链表的表头。
     1 *
     2  * 题目描述
     3  * 输入一个链表,反转链表后,输出新链表的表头。
     4  */
     5 
     6 public class Main15 {
     7 
     8     public static void main(String[] args) {
     9         // TODO Auto-generated method stub
    10         ListNode head = new ListNode(0);
    11         ListNode[] p = new ListNode[6];
    12         for(int i=0;i<p.length;i++) {
    13             p[i] = new ListNode(i+1);
    14             if(i>0) {
    15                 p[i-1].next = p[i];
    16             }else {
    17                 head = p[0];
    18             }
    19             //{1,2,3,4,5,6}
    20         }
    21         ListNode result = Main15.ReverseList(head);
    22         System.out.println(result.val);
    23     }
    24     
    25     public static class ListNode {
    26         int val;
    27         ListNode next = null;
    28 
    29         ListNode(int val) {
    30             this.val = val;
    31         }
    32     }
    33     
    34     public static ListNode ReverseList(ListNode head) {
    35         if (head == null) {
    36             return null;
    37         }
    38         
    39         ListNode next = null; //当前节点的后一个节点
    40         ListNode pre = null; //当前节点的前一个节点
    41         while (head != null) {
    42             next = head.next;
    43             head.next = pre;
    44             pre = head;
    45             head = next;
    46         }
    47         return pre;
    48     }
    49 
    50 }

    个人建议,自己画图走两个循环就很清楚了

  • 相关阅读:
    hdu 2647 Reward
    hdu 2094 产生冠军
    hdu 3342 Legal or Not
    hdu 1285 确定比赛名次
    hdu 3006 The Number of set
    hdu 1429 胜利大逃亡(续)
    UVA 146 ID Codes
    UVA 131 The Psychic Poker Player
    洛谷 P2491消防 解题报告
    洛谷 P2587 [ZJOI2008]泡泡堂 解题报告
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11083011.html
Copyright © 2011-2022 走看看