206. 反转链表
一、Java
class Solution {public ListNode reverseList(ListNode head) {if (head == null) return null;ListNode pre = null, cur = head, next = head.next;while (next != null) {cur.next = pre;pre = cur;cur = next;next = cur.next;}cur.next = pre;return cur;}
}
class Solution {public ListNode reverseList(ListNode head) {ListNode pre = null, cur = head, next;while (cur != null) {next = cur.next;cur.next = pre;pre = cur;cur = next;}return pre;}
}
class Solution {public ListNode reverseList(ListNode head) {if (head == null || head.next == null) return head;ListNode next = head.next, newHead = reverseList(next);head.next = null;next.next = head;return newHead;}
}
class Solution {public ListNode reverseList(ListNode head) {if (head == null || head.next == null) return head;ListNode newHead = reverseList(head.next);head.next.next = head;head.next = null;return newHead;}
}
二、C++
class Solution {
public:ListNode* reverseList(ListNode* head) {ListNode *pre = nullptr, *cur = head, *next;while (cur != nullptr) {next = cur->next;cur->next = pre;pre = cur;cur = next;}return pre;}
};
class Solution {
public:ListNode* reverseList(ListNode* head) {if (head == nullptr || head->next == nullptr) return head;ListNode *newHead = reverseList(head->next);head->next->next = head;head->next = nullptr;return newHead;}
};
三、Python
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:pre, cur, next = None, head, Nonewhile cur is not None:next = cur.nextcur.next = prepre = curcur = nextreturn pre
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:if head is None or head.next is None:return headnewHead = self.reverseList(head.next)head.next.next = headhead.next = Nonereturn newHead
四、JavaScript
var reverseList = function (head) {let pre = null, cur = head, next;while (cur != null) {next = cur.next;cur.next = pre;pre = cur;cur = next;}return pre;
};
var reverseList = function (head) {if (head == null || head.next == null) return head;let newHead = reverseList(head.next);head.next.next = head;head.next = null;return newHead;
};
五、Go
func reverseList(head *ListNode) *ListNode {var pre *ListNodecur := headfor cur != nil {next := cur.Nextcur.Next = prepre = curcur = next}return pre
}
func reverseList(head *ListNode) *ListNode {if head == nil || head.Next == nil {return head}newHead := reverseList(head.Next)head.Next.Next = headhead.Next = nilreturn newHead
}