【链表】LeetCode 206. 反转链表
题目链接
思路
先添加一个头结点real_head
。再设置real_head.next = null
,通过不断运用头插法将p
所指的结点插入到real_head.next
,完成反转操作。
代码
class Solution {
public ListNode reverseList(ListNode head) {
ListNode real_head = new ListNode(0, head);
ListNode p = real_head.next;
real_head.next = null;
while (p != null){
ListNode q = p.next;
p.next = real_head.next;
real_head.next = p;
p = q;
}
return real_head.next;
}
}