我写了两种
一种是在Solution里打印链表,Main直接调用方法
一种是在Main里写打印链表的方法,Solution里只返回LinkNode节点
法1
第一种Solution
public class Solution { public static ListNode reverseList(ListNode head) { ListNode dummy = new ListNode(0); ListNode curr = head;//头节点 while (curr != null) { ListNode next = curr.next;//下一个节点 curr.next = dummy.next;//反转链表头部 dummy.next = curr; curr = next; } return dummy.next;//反转后链表的头节点
}
}
第二种Solution
public class Solution { public static ListNode reverseList(ListNode head) { Stack<ListNode> stack = new Stack<>(); ListNode curr =head; while (curr != null) { stack.push(curr); curr = curr.next; } ListNode dummy = new ListNode(0,null); curr = dummy; while (!stack.isEmpty()) { ListNode node = stack.pop(); curr.next = new ListNode(node.val); curr = curr.next; } return dummy.next; }
public class Main { //打印链表的方法 public static void printList(ListNode head) { ListNode curr = head; while (curr != null) { System.out.print(curr.val + " "); curr = curr.next; } System.out.println(); } public static void main(String[] args) { // 创建示例链表: 1 -> 2 -> 3 -> 4 -> 5 ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); head.next.next.next.next = new ListNode(5); System.out.println("原链表:"); printList(head); // 反转链表 ListNode listNode = Solution.reverseList(head); System.out.println("反转后的链表:"); printList(listNode); } }
法2
使用栈的方式
public static void reverseList(ListNode head) { Stack<ListNode> stack = new Stack<>(); // 将链表中的节点依次压入栈中 ListNode current = head; while (current != null) { stack.push(current); current = current.next; } // 弹出栈中的节点并打印 while (!stack.isEmpty()) { System.out.print(stack.pop().val + " "); } }
public static void main(String[] args) { // 创建示例链表: 1 -> 2 -> 3 -> 4 -> 5 ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); head.next.next.next.next = new ListNode(5); // 反转链表 Solution.reverseList(head); }