原題:指針
Reverse a singly linked list.code
click to show more hints.get
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?it
既然問了可否iteratively or recursively, 那就both把.io
iterative 解法:class
總結就是獲得下一個節點,更改當前節點指向,將指針往下移動,直到過完整個linkedlist.cli
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode cur = head; while(cur!=null){ ListNode next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev; } }
recursive 解法:sed
總結是傳給helper method兩個節點,cur和pre(最開始是head和null), 先用n1存當前節點的next,而後把當前節點的next指向pre,而後一直recursively call help method直到過完整個linkedlist.List
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if(head == null||head.next== null) return head; return getReverse(head, null); } public ListNode getReverse(ListNode cur, ListNode prev){ if(cur.next == null){ cur.next = prev; return cur; } ListNode n1 = cur.next; cur.next = prev; return getReverse(n1,cur); } }