Sword refers to Offer linked list question collection

Print linked list from end to beginning

Printing connection

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
Problem description
Insert image description here

Idea 1:
My first idea is to traverse the linked list, store the value of each node in an array, and then store the array Perform inversion.

Insert image description here

Complexity analysis

Time complexity: O(n). Traverse the linked list in the forward direction.
Space complexity: O(n). An additional array is used to store each node in the linked list.

python3

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param listNode ListNode类 
# @return int整型一维数组
#
class Solution:
    def printListFromTailToHead(self , listNode: ListNode) -> List[int]:
        res = []
        while listNode:
            res.append(listNode.val)
            listNode = listNode.next
        return res[::-1]

C++

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
    
    
public:
    vector<int> printListFromTailToHead(ListNode* head) {
    
    
        vector<int> result;
        ListNode* current = head;
        while (current != nullptr) {
    
    
            result.push_back(current->val);
            current = current->next;
        }
        reverse(result.begin(), result.end());
        return result;
    }   
};

Reverse linked list

Question link:
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

Question description
Insert image description here

Idea 1:
Use double pointer iteration to change the next pointer of the current node to point to the previous node when traversing the linked list. Since a node has no reference to its previous node, its previous node must be stored beforehand. The latter node also needs to be stored before changing the reference. Finally, the new header reference is returned.
Insert image description here

Complexity analysis

Time complexity: O(n), traverse the linked list once in the forward direction.
Space complexity: O(1), constant space complexity.

python3

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @return ListNode类
#
class Solution:
    def ReverseList(self , head: ListNode) -> ListNode:
        # write code here
        pre , cur = None ,head
        while cur:
            # 暂存后继节点 cur.next
            tmp = cur.next
            # 修改 next 引用指向
            cur.next = pre
            # pre 暂存 cur
            pre = cur
            # cur 访问下一节点
            cur = tmp
        return pre

C++

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
    
    
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* ReverseList(ListNode* head) {
    
    
        ListNode *cur = head,*pre=nullptr;
        while(cur != nullptr){
    
    
            // 暂存后继节点 cur.next
            ListNode *tmp = cur->next;
            // 修改 next 引用指向
            cur->next = pre;
            // pre 暂存 cur
            pre = cur;
            // cur 访问下一节点
            cur = tmp;
        }
        return pre;
    }
};

Merge two sorted linked lists

Question link:
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

Question description
Insert image description here
Insert image description here

Idea 1:
Since the two linked lists are increasing, you can use double pointers to traverse the two linked lists through pHead1.val and pHead2. The size relationship of val determines the order in which nodes are added, and the two node pointers advance alternately until the traversal is completed.
Insert image description here

Complexity analysis

Time complexity: O(m+n), m,n are the lengths of the two linked lists respectively.
Space complexity: O(1), constant space complexity.

python3

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
        cur = head = ListNode(0)
        while pHead1 and pHead2:
            if pHead1.val <= pHead2.val:
                cur.next, pHead1 = pHead1, pHead1.next
            else:
                cur.next, pHead2 = pHead2, pHead2.next
            cur = cur.next
        cur.next = pHead1 if pHead1 else pHead2
        return head.next

C++

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
    
    
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead1 ListNode类 
     * @param pHead2 ListNode类 
     * @return ListNode类
     */
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
    
    
        ListNode *cur = new ListNode(0);
        ListNode *head = cur;
        while(pHead1 != nullptr && pHead2 != nullptr){
    
    
            if(pHead1->val <= pHead2->val){
    
    
                cur->next = pHead1;
                pHead1 = pHead1->next;
            }
            else{
    
    
                cur->next = pHead2;
                pHead2 = pHead2->next;
            }
            cur = cur->next;
        }
        cur->next = pHead1 ? pHead1 : pHead2;
        return head->next;
    }
};

Guess you like

Origin blog.csdn.net/JulyLi2019/article/details/134837270