---
title: "算法基础之单链表逆置"
author: "aaron-han"
date: "2012-04-20T14:58:56Z"
tags: []
categories: ["互联网"]
slug: "untitled"
draft: false
lastmod: "2012-04-20T14:58:56Z"
id: 1491478
url: "https://aaron-han.iteye.com/blog/1491478"
---

貌似各种笔试面试里这个挺爱考的，不清楚过程多画画图就明白了。
先写的单的，哪天把双链表逆置写一下。 :evil: 

```java

public class LinkedListReverse {

	/**
	 * 单链表逆置
	 * 
	 * @author aaron-han
	 * 
	 */
	public static void main(String[] args) {
		Node a = new Node("NodeA");
		Node b = new Node("NodeB");
		Node c = new Node("NodeC");
		Node d = new Node("NodeD");
		Node e = new Node("NodeE");

		a.next = b;
		b.next = c;
		c.next = d;
		d.next = e;

		System.out.println("original:");
		printNodes(a);
		Node head = reverse(a);
		System.out.println("after reverse:");
		printNodes(head);
	}

	public static Node reverse(Node node) {
		if (node == null) {
			return node;
		}
		Node head = node;
		Node pre = null;
		Node next = head.next;
		while (next != null) {
			head.next = pre;
			pre = head;
			head = next;
			next = next.next;
		}
		head.next = pre;
		return head;
	}

	public static void printNodes(Node node) {
		for (; node != null; node = node.next) {
			System.out.println(node.name);
		}
	}

	static class Node {
		String name;
		Node next;

		Node(String name) {
			this.name = name;
		}
	}

}

```