码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现单链表反转

时间:2014-09-01 14:06:03      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:单链表反转

本文主要介绍单链表反转的两种方法,记录如下:

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



Java实现单链表反转

标签:单链表反转

原文地址:http://blog.csdn.net/hjiam2/article/details/38978711

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!