Java反转单链表
- class Node {
- private int data;
- private Node nextNode;
- public Node(int data) {
- this.data = data;
- }
- public int getData() {
- return data;
- }
- public void setData(int data) {
- this.data = data;
- }
- public Node getNextNode() {
- return nextNode;
- }
- public void setNextNode(Node nextNode) {
- this.nextNode = nextNode;
- }
- }
- public class ReverseSingleList {
- public static Node reverse(Node head) {
- if (null == head || null == head.getNextNode()) {
- return head;
- }
- Node reversedHead = reverse(head.getNextNode());
- head.getNextNode().setNextNode(head);
- head.setNextNode(null);
- return reversedHead;
- }
- public static Node reverse2(Node head) {
- if (null == head || null == head.getNextNode()) {
- return head;
- }
- Node node1 = head;
- Node node2 = head.getNextNode();
- head.setNextNode(null);
- while (null != node2) {
- node1 = node2;
- node2 = node2.getNextNode();
- node1.setNextNode(head);
- head = node1;
- }
- return head;
- }
- public static void main(String[] args) {
- Node head = new Node(0);
- Node cur = head;
- Node tmp = null;
- // 构造一个长度为10的链表,保存头节点对象head
- for (int i = 1; i < 10; i++) {
- tmp = new Node(i);
- cur.setNextNode(tmp);
- cur = tmp;
- }
- //打印反转前的链表
- Node h = head;
- while (null != h) {
- System.out.print(h.getData() + " ");
- h = h.getNextNode();
- }
- //调用反转方法
- //head = reverse(head);
- head = reverse2(head);
- System.out.println("\n**************************");
- //打印反转后的结果
- while (null != head) {
- System.out.print(head.getData() + " ");
- head = head.getNextNode();
- }
- }
- }
运行结果:
0 1 2 3 4 5 6 7 8 9
**************************
9 8 7 6 5 4 3 2 1 0
学习时的痛苦是暂时的 未学到的痛苦是终生的