Reverse a singly linked list.
Solution 1:
思路:null的使用。用一个null node来承接,一个一个接上去即可。一刷的时候还觉得这node转化好麻烦好神奇,熟悉之后其实做起来很快。
/** * 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) { return head; } ListNode last=null; while(head!=null) { ListNode copy=head.next; head.next=last; last=head; head=copy; } return last; }}
Solution 2:
follow up : Use Recursion
思路:如果head.next不是null,递归head.next,注意先把head.next指针存好,方便于reverse之后接上head。因为返回的是一个listnode,用一个dummy node来把node用于输出。如果head.next是null的话,直接返回head即可。Recursion真的是一个神器!
/** * 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) { return head; } ListNode dummy=new ListNode(-1); if(head.next!=null) { ListNode copy=head.next; dummy.next=reverseList(head.next); copy.next=head; head.next=null; } else { return head; } return dummy.next; }}