题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
ListNode p=null,q=head;
while(q!=null && q.next!=null){
ListNode t = q.next;
q.next = p;
p = q;
q = t;
}
if(q!=null) q.next = p;
return q;
if(head==null || head.next==null){ //如果后面没有或者自己就没有了 递归出去
return head;
}
ListNode next = head.next; //next node
ListNode reverse = ReverseList(next);//不管具体细节 假设后面翻转结束
next.next = head;
head.next = null;
return reverse;
if(head==null) return null;
Stack<ListNode> st = new Stack<ListNode>();
while(head!=null){
st.push(head);
head = head.next;
}
ListNode ans = st.pop();
ListNode t = ans;
while(!st.isEmpty()){
ListNode tt = st.pop();
t.next = tt;
t = tt;
}
t.next = null;
return ans;