原题:指针
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); } }