Java数据结构之链表反转
2014-04-17 14:17
525 查看
思路很简单,定义一个类,这个类分成2块,一块是表示自身的标志,另外一个存储指向下一个元素的引用。通过互换相邻两个节点的引用来达到链表反转的效果。上代码:
运行打印结果:
1 2 3 4 5
5 4 3 2 1
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
相关文章推荐
- 数据结构之Java单链表反转
- 【Java数据结构】Java数据结构之链表反转
- 【Java数据结构】Java数据结构之链表反转
- JAVA数据结构---单链表
- 数据结构 反转单向链表和双向链表
- Java数据结构复习——链表
- 【数据结构】链表的原理及java实现
- java实现单链表反转(遍历方式)
- Java实现反转链表
- Java数据结构——链表
- java不用api实现单链表反转(二)
- JAVA实现链表的反转(《剑指offer》)
- java数据结构之链表
- Java/Go实现链表反转
- java反转链表实现
- 单链表的反转-Java实现
- java 数据结构-链表
- Java单链表反转与部分反转
- 数据结构Java实现04----循环链表、仿真链表
- 数据结构C语言>3基本链表>3-8链表结构的反转