题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
其实是很简单的题 呜呜 由于我太菜 不懂代码 搞了好一会
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode nh=null;//新链表表头
ListNode hp=head;
while(head!=null)
{
ListNode temp=head.next;
hp.next=nh;
nh=hp;
head=temp;
hp=head;
}
return nh;
}
}
我之前是这样写的
while(head!=null)
{
hp.next=nh;
nh=hp;
head=head.next;//这里 由于之前 hp=head 实际上指向了同一块地址 我让hp.next=nh=null 实际上head.next也指向了null...
hp=head;
}
}
解决方法是让一个temp值保存下head的next 用于更新head 晕 总体的方法使用的是头插法


查看3道真题和解析