Reverse a singly linked list.
Subscribe to see which companies asked this question.
利用循环。
1 public class Solution { 2 public ListNode reverseList(ListNode head) { 3 if(head == null ||head.next == null) return head; 4 ListNode pre = head; 5 head = head.next; 6 pre.next = null; 7 while(head != null){ 8 ListNode next = head.next; 9 head.next = pre; 10 pre = head; 11 head = next; 12 } 13 return pre; 14 } 15 }
递归版
1 public class Solution { 2 public ListNode reverseList(ListNode head) { 3 if(head == null ||head.next == null) return head; 4 ListNode pre = head; 5 head = head.next; 6 ListNode newhead = reverseList(head); 7 pre.next = null; 8 head.next = pre; 9 return newhead; 10 11 } 12 }