题目要求:Java实现一个双向链表的倒置功能(1->2->3 变成 3->2->1)
提交:代码、测试用例,希望可以写成一个Java小项目,可以看到单元测试部分
该题目的代码,已经放到了我的github上,地址为:https://github.com/jiashubing/alibaba-linkedlist-reversed.git
最关键的是自定义节点Node 和自定义双向链表MylinkedList 两个类,倒置的方法放在自定义链表类里reversed() ,具体的说明都在代码中
自定义节点类Node.java,有三个参数 :T data(当前值)、Node
自定义双向链表类MylinkedList.java,有两个参数:Node
添加节点的方法void add(T data):添加的第一个节点Node,它的左节点为null,最后一个节点的右节点也为null,中间的每个节点的左右节点都有值
倒置链表的方法reversed():把每个节点的左右节点交换,并且把链表的首尾节点也交换,就可以了。这里需要考虑的是循环的终止条件。我的实现如下:
public void reversed() {
if (head == null || head.getRight() == null) {
return;
}
current = head;
while(true) {
//交换左右节点
Node tmp = head.getLeft();
head.setLeft(head.getRight());
head.setRight(tmp);
//如果左节点为空,则终止,否则循环执行
if (head.getLeft() == null) {
return;
} else {
head = head.getLeft();
}
}
}
剩下的测试用例,就简单了。下面是我的github上的代码,记录下:
pom.xml
4.0.0 cn.jiashubing alitest1.0-SNAPSHOT junit junit4.12
Node.java
package cn.jiashubing; class Node{ private T data; private Node left; private Node right; Node(T data) { this.data = data; this.left = null; this.right = null; } T getData() { return data; } void setData(T data) { this.data = data; } Node getLeft() { return left; } void setLeft(Node left) { this.left = left; } Node getRight() { return right; } void setRight(Node right) { this.right = right; } }
MylinkedList.java
package cn.jiashubing; public class MylinkedList{ private Node head; private Node current; public void add(T data) { if (head == null) { head = new Node (data); current = head; } else { Node tmp = new Node (data); current.setRight(tmp); tmp.setLeft(current); current = current.getRight(); } } public void print(Node node) { if (node == null) { return; } Node tmp = node; while (tmp != null) { System.out.print(tmp.getData() + " "); tmp = tmp.getRight(); } System.out.println(""); } public void printRev(Node node) { if (node == null) { return; } Node tmp = node; while (tmp != null) { System.out.print(tmp.getData() + " "); tmp = tmp.getLeft(); } System.out.println(""); } public void reversed() { if (head == null || head.getRight() == null) { return; } current = head; while(true) { //交换左右节点 Node tmp = head.getLeft(); head.setLeft(head.getRight()); head.setRight(tmp); //如果左节点为空,则终止,否则循环执行 if (head.getLeft() == null) { return; } else { head = head.getLeft(); } } } public Node getHead() { return head; } public Node getCurrent() { return current; } }
JunitTest.java
import cn.jiashubing.MylinkedList;
import org.junit.Before;
import org.junit.Test;
public class JunitTest {
private MylinkedList list;
@Before
public void setNum() {
list = new MylinkedList();
for (int i = 1; i < 4; i++) {
list.add(i);
}
System.out.println("正向打印: ");
list.print(list.getHead());
}
@Test
public void test1() {
System.out.println("链表倒置后正向打印 ");
list.reversed();
list.print(list.getHead());
}
@Test
public void test2() {
System.out.println("逆向打印 ");
list.printRev(list.getCurrent());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



