反转链表,该链表为单链表。

head 节点指向的是头节点。

最简单的方法,就是建一个新链表,将原来链表的节点一个个找到,并且使用头插法插入新链表。时间复杂度也就是O(n),空间复杂度就需要定义2个节点。

一个节点prev指向新的链表头,另一个节点temp用来获取原始链表的数据。

 

public class Solution {
    /**
     * @param head: n
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
         
        ListNode prev = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
}

 

相关文章:

  • 2021-05-19
  • 2021-08-18
  • 2021-09-21
  • 2021-07-22
  • 2021-08-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-31
  • 2022-01-13
  • 2022-12-23
  • 2021-11-30
  • 2022-03-08
  • 2022-12-23
  • 2021-09-24
相关资源
相似解决方案