Try   HackMD

leetcode解題:(Easy) 206. Reverse Linked List

題目:https://leetcode.com/problems/reverse-linked-list/

描述:給定一個鏈結串列,回傳一個與之順序顛倒的鏈結串列

解題思路:這種問題畫圖模擬迭代過程應該是最簡單直覺也最好的方式,比較會卡住的部分是找出需要用多少個node來確保能順利迭代,以這題而言就需要3個(包含輸入給的head)

程式碼:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode pre = null; ListNode curr = null; while(head != null) { pre = curr; curr = head; head = head.next; curr.next = pre; } return curr; } }

時間複雜度:O(n)
空間複雜度:O(1)

tags: leetcode easy linked list