- 反转链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//双指针法:先定义两个指针pre和cur分别指向null和head,一个临时指针temp
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;
while (cur != null) {//循环遍历
//临时指针先存放cur.next,因为它等会会改变方向,避免丢失引用
temp = cur.next;
//改变指针指向,由指向后一个节点改为指向前一个节点
cur.next = pre;
//移动pre, cur向后移,继续后续的反转的过程
pre = cur;
cur = temp;
}
return pre;
}
}