Java/206. Reverse Linked List 反转链表

90 篇文章 0 订阅

题目


 

 

 

代码部分一(0ms 迭代)

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        
        ListNode node, temp;
        node = head.next;
        head.next = null;
        while(node.next != null){
            temp = node.next;
            node.next = head;
            head = node;
            node = temp;
        }
        node.next = head;
        head = node;
        
        return head;
    }
}

 

代码部分二(0ms 递归)

class Solution {
    ListNode node, temp;
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        
        ListNode res = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return res;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是Java实现反转双向链表的代码: ```java public class DoublyLinkedList { private Node head; private class Node { int data; Node prev; Node next; public Node(int data) { this.data = data; } } // 添加元素到双向链表的尾部 public void add(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; newNode.prev = current; } } // 反转双向链表 public void reverse() { Node current = head; Node temp = null; while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } if (temp != null) { head = temp.prev; } } // 输出双向链表 public void print() { Node current = head; while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } public static void main(String[] args) { DoublyLinkedList list = new DoublyLinkedList(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); System.out.print("Original List: "); list.print(); list.reverse(); System.out.print("Reversed List: "); list.print(); } } ``` 在这个实现中,我们定义了一个内部类 `Node` 来表示双向链表节点。在 `add` 方法中,我们添加一个新节点到链表尾部。在 `reverse` 方法中,我们使用三个指针 `current`, `temp`, 和 `prev` 来反转链表。在 `print` 方法中,我们遍历链表并打印每个节点的值。 在 `main` 方法中,我们创建一个新的 `DoublyLinkedList` 对象,并添加一些元素。然后,我们打印原始链表,调用 `reverse` 方法反转链表,并再次打印反转后的链表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值