在Java中反转链接列表

时间:2020-02-23 14:34:23  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中反转链接列表。

可以有两个解决方案来反转Java中的链接列表

  • 迭代
  • 递归

迭代

其逻辑是:

  • 有三个节点。比如:previousNode、currentNode,nextNode
  • currentNode为起始节点时,previousNode为空
  • 将 currentNode.next 赋值给 previousNode 以反转链接。
  • 在每次迭代中,将currentNode和previousNode移动1个节点。
public static Node reverseLinkedList(Node currentNode)
	{
		//For first node, previousNode will be null
		Node previousNode=null;
		Node nextNode;
		while(currentNode!=null)
		{
			nextNode=currentNode.next;
			//reversing the link
			currentNode.next=previousNode;
			//moving currentNode and previousNode by 1 node
			previousNode=currentNode;
			currentNode=nextNode;
		}
		return previousNode;
	}

Java程序撤消链接列表将是:

package org.igi.theitroad;
 
public class LinkedList{
 
	private Node head;
 
	private static class Node {
		private int value;
		private Node next;
 
		Node(int value) {
			this.value = value;
 
		}
	}
 
	public void addToTheLast(Node node) {
 
		if (head == null) {
			head = node;
		} else {
			Node temp = head;
			while (temp.next != null)
				temp = temp.next;
 
			temp.next = node;
		}
	}
 
 
	public void printList(Node head) {
		Node temp = head;
		while (temp != null) {
			System.out.format("%d ", temp.value);
			temp = temp.next;
		}
		System.out.println();
	}
 
	//Reverse linkedlist using this function 
	public static Node reverseLinkedList(Node currentNode)
	{
		//For first node, previousNode will be null
		Node previousNode=null;
		Node nextNode;
		while(currentNode!=null)
		{
			nextNode=currentNode.next;
			//reversing the link
			currentNode.next=previousNode;
			//moving currentNode and previousNode by 1 node
			previousNode=currentNode;
			currentNode=nextNode;
		}
		return previousNode;
	}
 
	public static void main(String[] args) {
		LinkedList list = new LinkedList();
		//Creating a linked list
		Node head=new Node(5);
		list.addToTheLast(head);
		list.addToTheLast(new Node(6));
		list.addToTheLast(new Node(7));
		list.addToTheLast(new Node(1));
		list.addToTheLast(new Node(2));
 
		list.printList(head);
		//Reversing LinkedList
		Node reverseHead=reverseLinkedList(head);
		System.out.println("After reversing");
		list.printList(reverseHead);
 
	}
 
}

运行上面的程序,我们将获取以下输出:

5 6 7 1 2 
After reversing
2 1 7 6 5

递归

基本情况:基本情况为此为null为null或者node.next为null

对于递归解决方案,将上述程序的ReverselinkedList替换为以下函数

public static Node reverseLinkedList(Node node) {
		if (node == null || node.next == null) {
			return node;
		}
 
		Node remaining = reverseLinkedList(node.next);
		node.next.next = node;
		node.next = null;
		return remaining;
	}