diff --git a/notes/面试总结.md b/notes/面试总结.md index 35b7aa3a..184a80d6 100644 --- a/notes/面试总结.md +++ b/notes/面试总结.md @@ -26,6 +26,8 @@ * [21. 调整数组顺序使奇数位于偶数前面](#21-调整数组顺序使奇数位于偶数前面) * [22. 链表中倒数第 K 个结点](#22-链表中倒数第-k-个结点) * [23. 链表中环的入口结点](#23-链表中环的入口结点) +* [24. 反转链表](#24-反转链表) +* [25. 合并两个排序的链表](#25-合并两个排序的链表) * [参考文献](#参考文献) @@ -1790,6 +1792,179 @@ class Solution: if pHead in plist: return pHead ``` +# 24. 反转链表 + +[NowCoder](https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking) + +## 解题思路 + +### 递归 + +```java +public ListNode ReverseList(ListNode head) { + if (head == null || head.next == null) + return head; + ListNode next = head.next; + head.next = null; + ListNode newHead = ReverseList(next); + next.next = head; + return newHead; +} +``` + +```python +# -*- coding:utf-8 -*- +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None +class Solution: + # 返回ListNode + def ReverseList(self, pHead): + # write code here + if pHead == None or pHead.next == None: + return pHead + next = pHead.next + pHead.next = None + newHead = self.ReverseList(next) + next.next = pHead + return newHead +``` + +### 迭代 + +```java +public ListNode ReverseList(ListNode head) { + ListNode newList = new ListNode(-1); + while (head != null) { + ListNode next = head.next; + head.next = newList.next; + newList.next = head; + head = next; + } + return newList.next; +} +``` + +```python +# -*- coding:utf-8 -*- +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None +class Solution: + # 返回ListNode + def ReverseList(self, pHead): + # write code here + newList = ListNode(-1) + while pHead: + next = pHead.next + pHead.next = newList.next + newList.next = pHead + pHead = next + return newList.next +``` + +# 25. 合并两个排序的链表 + +[NowCoder](https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tqId=11169&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking) + +## 题目描述 + +