206.反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例1
1 2
| 输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
|
示例2
示例3
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public class ListNode {
int val; ListNode next;
ListNode() { }
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
public static void main(String[] args) {
ListNode head = new ListNode(1, new ListNode(2, new ListNode(3)));
ListNode reverseList = reverseList(head); while (Objects.nonNull(reverseList)) { System.out.println(reverseList.val); reverseList = reverseList.next; } }
public static ListNode reverseList(ListNode head) { if (head == null) { return null; }
ListNode prev = null; while (head != null) { ListNode next = head.next; head.next = prev; prev = head; head = next; } return prev; } }
|