Reverse a singly linked 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;
ListNode nextNode = head.next ;
ListNode newHead = reverseList(head.next);
nextNode.next = head ;
head.next = null;
return newHead;
}
}
方法二:非递归
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null||head.next==null) return head;
ListNode prev = head;
ListNode temp = prev.next;
while(temp != null){
ListNode next = temp.next;
temp.next = prev;
prev = temp;
temp = next;
}
head.next = null;
return prev;
}
}