206. Reverse Linked List 反轉連結串列
阿新 • • 發佈:2018-11-07
題目
程式碼部分一(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; } }