408 King's Road Data Structure After-Class Code Exercises (9)

Get into the habit of writing together! This is the 13th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the event details .

I plan to update the implementation of all after-school code exercises in the 23 King's Road data structure. Although the exams are generally written in pseudocode, I have implemented all of them for obsessive-compulsive disorder. The warehouse is here.

  • Linear Table 14/14
  • Linked List 5/25

2.3.7, 3

image.png

  • Classic recursion, the exit is still an empty node
  • Use the recursive stack to reverse the output of the node value
  • Time complexity O(n), space complexity O(n)
void reversePrintList(LinkList L) {
  if (L == NULL) return;
  reversePrintList(L->next);
  cout << L->data << " ";
}
复制代码
  • Traverse the entire linked list from beginning to end, use the stack to store the value of each node and then output it
  • Time complexity O(n), space complexity O(n)
void reversePrintList2(LinkList L) {
  if (L == NULL) return;
	
  // 1.遍历存储
  stack<int> stack;
  while (L != NULL) {
    stack.push(L->data);
    L = L->next;
  }
  
  // 2.输出
  while (!stack.empty()) {
    cout << stack.top() << " ";
    stack.pop();
  }
}
复制代码

2.3.7, 4

image.png

  • It is basically the same as finding the minimum value in the sequence table, but you need to add a pointer to the prefix to facilitate deletion
  • Define double pointers: p and prefix pre, and define minp and minpre to point to the current minimum node
  • Time complexity O(n), space complexity O(1)
void delMin(LinkList &L) {
  // 1.定义指针
  LNode *pre = L, *p = pre->next;
  LNode *minpre = pre, *minp = p;

  // 2.找到最小值
  while (p != NULL) {
    if (p->data < minp->data) {
      minpre = pre;
      minp = p;
    }
    pre = p;
    p = p->next;
  }

  // 3.删除最小值
  minpre->next = minp->next;
  free(minp);
}
复制代码

2.3.7, 5

image.png

  • In-place inversion, for a linked list with a head node, is to insert the nodes after the head node according to the head insertion method
  • Still a double pointer, this time requires p and the suffix of p (drawing is easier to understand)
  • The head plug means that every time a new p is inserted behind the L ! In this way, L is still the head node, and there is no need to return a new linked list
  • Time complexity O(n), space complexity O(1)
void reverse(LinkList &L) {
  LNode *p = L->next, *q;
  L->next = NULL;

  while (p != NULL) {
    q = p->next;  // 记录后缀

    p->next = L->next;  // 插到L后面
    L->next = p;

    p = q;  // 继续插入下一个结点
  }
}
复制代码

Guess you like

Origin juejin.im/post/7086641011564216351