思路:3个指针来控制,listNext指针指向下下
一个节点,head 和pre指针确保前面2个节点的反转。
static ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode reverseHead = head;
ListNode listNext = head.next;
ListNode pre = null;
if (listNext == null) {
return head;
}
while (listNext != null) {
pre = listNext;
listNext = listNext.next;
pre.next = reverseHead;
if (reverseHead == head)
reverseHead.next = null;
reverseHead = pre;
}
return reverseHead;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
node1.next = node2;
ListNode node3 = new ListNode(3);
node2.next = node3;
ListNode node4 = new ListNode(4);
node3.next = node4;
ListNode node5 = new ListNode(5);
node4.next = node5;
ListNode node6 = new ListNode(6);
node5.next = node6;
ListNode node = reverseList(node1);
while (node.next!=null) {
System.out.println(node.value);
node = node.next;
}
System.out.println(node.value);
}