package com.bittech.Linked;
public class MySingleListImpl {
class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head;
public MySingleListImpl() {
this.head = null;
}
public void addFirst(int data) {
Node node = new Node(data);
if (this.head == null) {
this.head = node;
}else {
node.next = this.head;
this.head = node;
}
}
public void addLast(int data) {
Node node = new Node(data);
if (this.head == null) {
this.head = node;
}else {
Node cur = this.head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
public void display() {
Node cur = this.head;
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
System.out.println();
}
public Node reverseList() {
Node reverseHead = null;
Node prev = null;
Node cur = this.head;
while (cur != null) {
Node curNext = cur.next;
if (curNext == null) {
reverseHead = cur;
}
cur.next = prev;
prev = cur;
cur = curNext;
}
return reverseHead;
}
public void show(Node newHead) {
Node cur = newHead;
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
System.out.println();
}
}
package com.bittech.Linked;
public class Test {
public static void main(String[] args) {
MySingleListImpl list = new MySingleListImpl();
list.addFirst(134);
list.addFirst(20);
list.addFirst(35);
list.addLast(10);
list.addLast(999);
list.addLast(7);
System.out.print("原链表:");
list.display();
MySingleListImpl.Node newNode = list.reverseList();
System.out.print("反转后的链表:");
list.show(newNode);
}
}