import java.util.Arrays;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
/**
* @class_name: ReverseLinklist
* @description: 链表操作
* @author: ljk
* @create: 2021-11-18 19:58
**/
public class ReverseLinklist {
/**
* 对链表进行翻转并返回一个数组
*
* @param head 待处理链表头节点
* @return 返回一个倒序的数组
*/
public static int[] reversePrint(ListNode head) {
int len = 0;
ListNode temp = head;
while (temp != null) {
len++;
temp = temp.next;
}
int[] result = new int[len];
while (len > 0) {
result[--len] = head.val;
head = head.next;
}
return result;
}
/**
* 对链表进行翻转,然后返回其头节结点
*
* @param head 待处理链表头节点
* @return 返回一个倒置的链表的头节点
*/
public static ListNode reverseLinkList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
/**
* 给出链表的头节点,然后进行输出链表内容
*
* @param head
*/
public static void printListNode(ListNode head) {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.val + " ");
temp = temp.next;
}
}
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
l1.next = l2;
l2.next = l3;
// 得到逆序的数组
int[] result = reversePrint(l1);
System.out.println(Arrays.toString(result));
// 得到反转后的链表
ListNode head = reverseLinkList(l1);
printListNode(head);
}
}
java 实现输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
最新推荐文章于 2022-01-21 22:20:36 发布