206_反转链表

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

206_反转链表

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

206_反转链表

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

解题思路:

  1. 申请一个pre指向null
  2. 遍历节点到null
  • 先保存当前节点下一个节点

  • 把当前节点的下一节点指向pre

  • 把pre指向当前节点

     

     

class Solution {
    public ListNode reverseList(ListNode head) {
        // corner case
        if (head == null || head.next == null) {
            return head;
        }

        // normal case
        ListNode pre = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

  

 

206_反转链表

上一篇:Jmeter 介绍、安装、配置


下一篇:网络丢包专题