题目描述
输入一个链表,反转链表后,输出新链表的表头。
/*
public 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 head;
}
// 使用3个指针表示紧挨着的3个节点,然后每次倒置第1 2个节点的关系
ListNode second = head.next;
head.next = null;
ListNode three = null;
while (second != null) {
three = second.next;
second.next = head;
head = second;
second = three;
}
return head;
}
}
网友评论