题目描述
输入一个链表,反转链表后,输出新链表的表头,反转后的结果如下图所示。
思路分析
从前往后遍历原链表,把遍历出来的节点设置为反转后链表的首节点,当原链表遍历完毕,那 么就等到了反转后的链表。
代码实现
节点类
package day04;
import lombok.Data;
@Data
public class Node {
private Object data;
private Node next;
public Node(Object data) {
this.data = data;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
}
实现类
package day04;
public class ReverseLinkedList {
public static void main(String[] args) {
Node lastNode = new Node(44);
Node node3 = new Node(33,lastNode);
Node node2 = new Node(22,node3);
Node headNode = new Node(11,node2);
System.out.print("反转之前:");
print(headNode);
System.out.println();
Node reverse = reversLinked(headNode);
System.out.print("反转后:");
print(reverse);
}
public static Node reversLinked(Node headNode){
if (headNode == null || headNode.getNext() == null)
return headNode;
Node reverse = null;
while (headNode != null){
Node nextNode = headNode.getNext();
headNode.setNext(reverse);
reverse = headNode;
headNode = nextNode;
}
return reverse;
}
public static void print(Node headNode){
Node tempNode = headNode;
while (tempNode != null){
System.out.print(tempNode.getData()+" ");
tempNode = tempNode.getNext();
}
}
}
|