[LeetCode]206. Reverse Linked List(链表反转)

时间:2023-03-09 06:50:53
[LeetCode]206. Reverse Linked List(链表反转)

Reverse a singly linked list.

click to show more hints.

Subscribe to see which companies asked this question.

利用循环。

 public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ||head.next == null) return head;
ListNode pre = head;
head = head.next;
pre.next = null;
while(head != null){
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}

递归版


 public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ||head.next == null) return head;
ListNode pre = head;
head = head.next;
ListNode newhead = reverseList(head);
pre.next = null;
head.next = pre;
return newhead; }
}