反转链表
题目
输入一个链表,反转链表后,输出新链表的表头。
思想
如果链表为空,则输出空,否则逆置输出,头插法(中间注释掉的部分我觉得和下面部分写的一样,但是没通过且没找到原因)。
代码
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode q = head.next;
ListNode p = head;
p.next = null;
// while(q != null){
// ListNode temp = q;
// temp.next = p;
// p = temp;
// q = q.next;
// }
while (q != null){
ListNode temp = q.next;
q.next = p;
p = q;
q = temp;
}
return p;
}