206.反转链表
力扣题目链接
题意:反转一个单链表。
示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
前两天刚做过hhhhh
package com.programmercarl.linkedlist;
import com.programmercarl.linkedlist.domain.ListNode;
public class ReverseLinkedList {
public static void main(String[] args) {
ListNode node5 = ListNode.builder().val(5).next(null).build();
ListNode node4 = ListNode.builder().val(4).next(node5).build();
ListNode node3 = ListNode.builder().val(3).next(node4).build();
ListNode node2 = ListNode.builder().val(2).next(node3).build();
ListNode node1 = ListNode.builder().val(1).next(node2).build();
System.out.println( reverseList(node1));
}
public static ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
if (head.next.next == null) {
ListNode newHead = head.next;
newHead.next = head;
head.next = null;
return newHead;
}
ListNode leftHead = new ListNode(0, head);
ListNode rightHead = new ListNode(0, head.next);
ListNode rightSecond =head.next.next;
head.next = null;
while (rightSecond != null) {
rightHead.next.next = leftHead.next;
leftHead.next = rightHead.next;
rightHead.next = rightSecond;
rightSecond = rightSecond.next;
}
rightHead.next.next = leftHead.next;
return rightHead.next;
}
}
|