反转链表的两种方法

我写了两种

一种是在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);
    }

  • 14
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值