您的位置:首页 > 理论基础 > 数据结构算法

Java数据结构之链表反转

2014-04-17 14:17 525 查看
思路很简单,定义一个类,这个类分成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 + "\t");
p = p.next;
}
System.out.print("\n");
}
}
}

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: