Tag:List
Difficulty:Easy
Problem
反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
Solution
设置一个新的头节点,然后遍历链表,每次插入到头节点后面
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode res = new ListNode(-1);
ListNode p = null;
while (head != null) {
p = head.next;
head.next = res.next;
res.next = head;
head = p;
}
return res.next;
}