目录
LeetCode-206题
给定一个单链表的头节点,请反转链表,并返回反转后的链表
class Solution {
public ListNode reverseList(ListNode head) {
// check
if (head == null || head.next == null)
return head;
// 双指针
ListNode p1 = head;
ListNode p2 = head.next;
// 一直到p2指向null
while (p2 != null) {
ListNode curr = p1;
p1 = p2;
if (curr == head) {
curr.next = null;
}
// 定义一个临时变量存放此时p2的下一个节点
ListNode tmp = p2.next;
p2.next = curr;
p2 = tmp;
}
return p1;
}
private static class ListNode {
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}