题目:定义一个链表的头结点,反转该链表并输出反转后链表的头结点。
思路:定义三个指针:中心结点的前结点(记录next需要转移到的位置),中心结点,中心结点(暂存,防止链表断裂)。将中心结点的next指针设置为中心结点的前结点。
特殊情况:
- 空链表。
- 两个结点。
注意:修改完后,head的next指针置空。最后一个节点的next指针置为前一个结点。
public static ListNode reverseList(ListNode head) {
if (head==null || head.next==null)
return head;
if (head.next.next == null) {
ListNode temp = head.next;
temp.next = head;
head.next = null;
return temp;
}
ListNode p1 = head;
ListNode p2 = head.next;
ListNode p3 = head.next.next;
while (p3 != null) {
p2.next = p1;
p1 = p2;
p2 = p3;
p3 = p3.next;
}
p2.next = p1;
head.next = null;
return p2;
}