Reverse a singly linked list.
Subscribe to see which companies asked this question.
利用循环。
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ||head.next == null) return head;
ListNode pre = head;
head = head.next;
pre.next = null;
while(head != null){
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
递归版
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ||head.next == null) return head;
ListNode pre = head;
head = head.next;
ListNode newhead = reverseList(head);
pre.next = null;
head.next = pre;
return newhead; }
}