今天在刷算法题时,对于反转链表,还是不能够理解
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null){
return null;
}
ListNode newHead = null;
ListNode next = null;
while(head != null){
next = head.next; //保存断裂后原始链表的头节点
head.next = newHead; //改变指针指向方向,将当前节点指向反转链表的头节点
newHead = head; // newHead 指向反转链表的新的头节点
head = next; //继续循环
}
return newHead;
}
}
}
不能理解的地方如下,参考资料: https://blog.csdn.net/coder_kirito/article/details/99659392
head.next = newHead; //改变指针指向方向,将当前节点指向反转链表的头节点
newHead = head; // newHead 指向反转链表的新的头节点
head = next; //继续循环