题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
代码1:
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode root = new ListNode(0);
ListNode n=root;
while(head!=null){
n=head;
head=head.next;
n.next=null;
n.next=root.next;
root.next=n;
}
return root.next;
}
}
方法2
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}