zoukankan      html  css  js  c++  java
  • 【Java数据结构】Java数据结构之链表反转

    我们都知道用C可以很简单的实现单链表反转,今天来学习下,在Java中如何实现链表反转。

    思路很简单,定义一个类,这个类分成2块,一块是表示自身的标志,另外一个存储指向下一个元素的引用。通过互换相邻两个节点的引用来达到链表反转的效果。上代码:

    package com.withiter.test;
    
    public class ReverseList {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Node nodeLink = add("1", null);
    		add("2", nodeLink);
    		add("3", nodeLink);
    		add("4", nodeLink);
    		add("5", nodeLink);
    		print(nodeLink);
    		nodeLink = reverse(nodeLink);
    		print(nodeLink);
    	}
    
    	public static Node add(String name, Node head) {
    		if (head == null) {
    			return new Node(name);
    		} else {
    			Node p = head;
    			while (p.next != null) {
    				p = p.next;
    			}
    			p.next = new Node(name);
    			return head;
    		}
    	}
    
            // 反转的核心方法
    	public static Node reverse(Node head){
    		if(head == null){
    			return null;
    		}
    		Node p = head;
    		Node q = head.next;
    		p.next = null;
    		while(q != null){
    			Node temp = q.next;  
                q.next = p;  
                p = q;  
                q = temp;  
    		}
    		
    		return p;
    	}
    	
    	public static void print(Node head) {
    		if (head == null) {
    			System.out.println("null");
    		} else {
    			Node p = head;
    			while (p != null) {
    				System.out.print(p.name + "	");
    				p = p.next;
    			}
    			System.out.print("
    ");
    		}
    	}
    }
    
    class Node {
    
    	public Node(String name) {
    		super();
    		this.name = name;
    	}
    
    	public String name; // 自身标志
    	public Node next; // 指向下一个节点的引用
    }

    运行打印结果:

    1    2    3    4    5    
    5    4    3    2    1    


  • 相关阅读:
    试题 E: 迷宫
    对拍程序
    人群中钻出个光头
    HDU-魔咒词典(字符串hash)
    第八集 你明明自己也生病了,却还是要陪着我
    智力问答 50倒计时
    数据结构
    LeetCode刷题 fIRST MISSING POSITIVE
    LeetCode Best to buy and sell stock
    LeetCode Rotatelmage
  • 原文地址:https://www.cnblogs.com/james1207/p/3306430.html
Copyright © 2011-2022 走看看