AcWing 35. 反转链表
原题链接
简单
作者:
jkm
,
2021-03-27 15:38:50
,
所有人可见
,
阅读 243
迭代版实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode pre = head;
ListNode cur = pre.next;
while (cur != null) {
ListNode pos = cur.next;
cur.next = pre;
pre = cur;
cur = pos;
}
head.next = null;
return pre;
}
}
递归版实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode tail = reverseList(head.next);
head.next.next = head;
head.next = null;
return tail;
}
}