如今的我焦虑的停不下来 2020.04.20
题目:
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
点击链接
解题思路:
在单链表的表头临时接入一个节点,然后进行头插法操作。反转单链表。
package Offer16;
public class ReverseLinkedList {
public static class ListNode {
int value;
ListNode next = null;
}
public static ListNode reverseList(ListNode head) {
ListNode rootNode = new ListNode();
ListNode nextNode = null;
while(head != null) {
nextNode = head.next;
head.next = rootNode.next;
rootNode.next = head;
head = nextNode;
}
return rootNode.next;
}
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.value + "->");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
ListNode head = new ListNode();
head.value = 1;
head.next = new ListNode();
head.next.value = 2;
head.next.next = new ListNode();
head.next.next.value = 3;
head.next.next.next = new ListNode();
head.next.next.next.value = 4;
head.next.next.next.next = new ListNode();
head.next.next.next.next.value = 5;
printList(head);
head = reverseList(head);
printList(head);
}
}
个人认为算法思路才是最重要,但是有时候也会感觉这种链接节点的方式不好看,我又用面向对象的思想重构了一遍
package Offer16;
class Node {
int value;
Node next = null;
public Node(int value) {
this.value = value;
}
public Node() {
}
}
class LinkedList {
Node rootNode = null;
// 尾插法
public boolean insert(Node newNode) {
if (rootNode == null) {
rootNode = newNode;
return true;
}
Node currentNode = rootNode;
Node parentNode = null;
while (currentNode != null) {
parentNode = currentNode;
currentNode = currentNode.next;
}
parentNode.next = newNode;
return true;
}
public void order() {
Node currentNode = rootNode;
while(currentNode != null) {
System.out.println("\t" + currentNode.value);
currentNode = currentNode.next;
}
}
public Node Reverse(Node head) {
rootNode = new Node();
Node nextNode = null;
while (head != null) {
nextNode = head.next;
head.next = rootNode.next;
rootNode.next = head;
head = nextNode;
}
return rootNode.next;
}
}
public class ReverseLinkedList {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.insert(new Node(1));
linkedList.insert(new Node(2));
linkedList.insert(new Node(3));
linkedList.insert(new Node(4));
linkedList.order();
LinkedList linkedList2 = new LinkedList();
linkedList.rootNode = linkedList2.Reverse(linkedList.rootNode);
linkedList.order();
}
}