/**
* 3.单链表的翻转(腾讯)
* @param head 需要翻转列表的头结点
* @return 翻转后链表的头结点
*/
public static HeroNode turnList(HeroNode head) {
//首先new end 节点
//每读取一个新节点,就添加到第一个位置
//返回end
if (head.next == null) {
System.out.println("链表为空~");
return null;
}
HeroNode end = new HeroNode(0, "", "");//新节点
int numList = numList(head);//计算此链表的长度
HeroNode curH = head.next;//辅助节点,用于遍历
for (int i = 0; i < numList; i++) {
//保存新节点的值
HeroNode node = curH;
//1
curH = curH.next;
//2
node.next = end.next;
end.next = node;
}
return end;
}
可以看看https://leetcode-cn.com/problems/UHnkqh/
为什么改变node节点的next,curH也会改变?
这是java浅拷贝吧
以下是我的解法
public ListNode reverseList(ListNode head) {
ListNode reverse=null;
ListNode cur=head;
while(cur!=null){
ListNode ne=cur.next;
cur.next=reverse;
reverse=cur;
cur=ne;
}
return reverse;
}
都还没遍历到尾就保存新指针了,end.next是空,你让curh next等于end next不就是为空吗,然后curh等于它的next,那就是它为空了。不知道你想写什么,连指针都没有的,结构也不放出来,就这样了。