太經典的題目了,我就不廢話了,只是爲了po這個我非常obsessed的方法:
/**
* 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 second = head.next;
head.next=null;
ListNode rest = reverseList(second);
second.next = head;
return rest;
}
}
public ListNode reverseList(ListNode head) {
if(head==null || head.next == null)
return head;
ListNode p1 = head;
ListNode p2 = head.next;
head.next = null;
while(p1!= null && p2!= null){
ListNode t = p2.next;
p2.next = p1;
p1 = p2;
if (t!=null){
p2 = t;
}else{
break;
}
}
return p2;
}