链表的节点数据结构:
package cn.yaunsine.domain;
/**
* 链表节点数据结构
*/
public class ListNode {
/**
* 元素值
*/
public int val;
/**
* 指向下一个节点的指针
*/
public ListNode next;
public ListNode (int val) {
this.val = val;
this.next = null;
}
}
创建链表,反转链表,打印反转前后的链表
import cn.yaunsine.domain.ListNode;
import org.junit.Test;
/**
* 反转链表
* @author yaunsine
*/
public class ReverseListNode {
/**
* 打印链表
* @param root 头节点
*/
private void print(ListNode root) {
ListNode node = root;
while (node != null) {
System.out.print(node.val);
node = node.next;
}
System.out.println();
}
/**
* 反转链表
* @param node 翻转前的头节点
* @return 反转后的头节点
*/
ListNode reverse(ListNode node) {
if (node == null || node.next == null) {
return node;
}
ListNode tail = reverse(node.next);
node.next.next = node;
node.next = null;
return tail;
}
/**
* 把数组转为链表
* @param nums 数组
* @return 链表
*/
ListNode createListNode(int[] nums) {
ListNode head = new ListNode(-1);
ListNode tail = head;
for (int i = 0; i < nums.length; i++) {
ListNode node = new ListNode(nums[i]);
tail.next = node;
tail = tail.next;
}
return head.next;
}
/**
* 测试方法
*/
@Test
public void testNode() {
int[] nums = {3, 8, 2, 1, 5, 4};
ListNode head = createListNode(nums);
print(head);
head = reverse(head);
print(head);
}
}