zoukankan      html  css  js  c++  java
  • Java单链逆转

    本文介绍两种方法单向链表反转。记录,如下面:

    1.

    package com.leetcode;
    
    public class ListReverse {
    
    	public static void main(String[] args) {
    		Node node1 = new Node(1);
    		Node node2 = new Node(2);
    		Node node3 = new Node(3);
    		Node node4 = new Node(4);
    		node1.next = node2;
    		node2.next = node3;
    		node3.next = node4;
    		
    		Node head = reverse(node1);
    		while(head != null){
    			System.out.println(head.val);
    			head = head.next;
    		}
    		
    	}
    	
    	public static Node reverse(Node head){
    		Node cur = head, post = head.next;
    		head.next = null;
    		while(post != null){
    			Node tmp = post;
    			post = post.next;
    			tmp.next = cur;
    			cur = tmp;
    		}
    		return cur;
    	}
    	
    	static class Node{
    		int val;
    		Node next;
    		Node(int val){
    			this.val = val;
    			this.next = null;
    		}
    	}
    
    }
    

    执行结果为:

    4
    3
    2
    1

    2.

    package com.leetcode;
    
    public class ListReverse {
    
    	public static void main(String[] args) {
    		Node node1 = new Node(1);
    		Node node2 = new Node(2);
    		Node node3 = new Node(3);
    		Node node4 = new Node(4);
    		node1.next = node2;
    		node2.next = node3;
    		node3.next = node4;
    		
    		Node head = reverse(node1);
    		while(head != null){
    			System.out.println(head.val);
    			head = head.next;
    		}
    		
    	}
    	
    	public static Node reverse(Node head){
    		Node dummy = new Node(-1);
    		dummy.next = head;
    		Node pre = dummy, cur = head, post = head.next;
    		while(post != null){
    			cur.next = post.next;
    			post.next = pre.next;
    			pre.next = post;
    			post = cur.next;
    		}
    		return dummy.next;
    	}
    	
    	static class Node{
    		int val;
    		Node next;
    		Node(int val){
    			this.val = val;
    			this.next = null;
    		}
    	}
    
    }
    

    执行结果为:

    4
    3
    2
    1



    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    Linux 安装Zookeeper<集群版>(使用Mac远程访问)
    04寻找两个数组的中位数
    28实现strSTR()
    125验证回文串
    124,二叉树中的最大路径和
    123买卖股票的最佳时机III
    02爬取豆瓣最受欢迎的250部电影
    01爬取当当网500本五星好评书籍
    112买卖股票的最佳时机II
    121.买卖股票的最佳时机
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4822056.html
Copyright © 2011-2022 走看看