LeetCode第206题:反转链表
解题思录
假如链表结构:A->B->C->D->E->F->G
- 将相邻的两个元素的指针反转,如:A->B ,变成 B->A
prve = A
curr = B
curr.next = prve
- 如果B->A,那么->C的部分将丢失,需要临时变量记录C。
prve = A
curr = B
// 先记录,后指向
temp = curr.next
curr.next = prve
- A,B反转结束后,需要移动指针到下一个元素 C
prve = curr
curr = temp
整体代码:
public static ListNode reverseList(ListNode head) {
ListNode prve = null;
ListNode curr = head;
ListNode next = null;
while (curr != null){
//反指
next = curr.next;
curr.next = prve;
//下一个
prve = curr;
curr = next;
}
return prve;
}