Explorar o código

链表第一题,对c++的传参加深了理解

DESKTOP-C21C1Q8\tangs %!s(int64=6) %!d(string=hai) anos
pai
achega
6a195c08a0
Modificáronse 1 ficheiros con 134 adicións e 0 borrados
  1. 134 0
      2/2/1/main.cpp

+ 134 - 0
2/2/1/main.cpp

@@ -0,0 +1,134 @@
+//
+// Created by tangs on 2018/9/28.
+//
+
+#include <iostream>
+
+using namespace std;
+
+typedef struct LNode {
+    int data;
+    struct LNode *next;
+
+    LNode() {
+        this->data = -1;
+        this->next = NULL;
+    }
+
+    LNode* InitList(int length) {
+        // 初始化链表
+        LNode *L = new LNode();
+        L->data = 1;
+        L->next = NULL;
+        LNode *temp = L;
+        for (int i = 2; i <= length; i++) {
+            LNode *p = new LNode();
+            p->data = i;
+            p->next = NULL;
+            temp->next = p;
+            temp = temp->next;
+        }
+
+        for (int i = 1; i <= length; i++) {
+            LNode *p = new LNode();
+            p->data = i;
+            p->next = NULL;
+            temp->next = p;
+            temp = temp->next;
+        }
+        return L;
+    }
+
+    void Print() {
+        LNode *p = this;
+        while (p != NULL) {
+            cout << p->data << " ";
+            p = p->next;
+        }
+        cout << endl;
+    }
+} LNode;
+
+/**
+ *
+ * @param LinkList
+ * @param x
+ * @return
+ *
+ * 这是一个错误的函数,参数的*,值传递,不会改变外部的值。所以在@1处执行的语句会不生效。
+ */
+LNode* TrimRepeat(LNode *LinkList, int x) {
+    if (LinkList == NULL) {
+        return LinkList;
+    }
+    if (LinkList->data == x) {
+        // @1
+        LinkList = LinkList->next;
+    } else {
+        if (LinkList->next == NULL) {
+            return LinkList;
+        }
+        if (LinkList->next->data == x) {
+            LinkList->next = LinkList->next->next;
+        }
+    }
+    return TrimRepeat(LinkList->next, x);
+}
+
+
+/**
+ *
+ * @param LinkList 无头结点的单链表
+ * @param x 目标元素值
+ *
+ * 递归删除单链表中的元素x
+ */
+int TrimRepeat2(LNode* &LinkList, int x) {
+    if (LinkList == NULL) {
+        return 1;
+    }
+    if (LinkList->data == x) {
+        LinkList = LinkList->next;
+    } else {
+        if (LinkList->next == NULL) {
+            return 1;
+        }
+        if (LinkList->next->data == x) {
+            LinkList->next = LinkList->next->next;
+        }
+    }
+    return TrimRepeat2(LinkList->next, x);
+}
+
+/**
+ * 设计一个递归算法,删除不带头结点的单链表L中所有值为x的结点
+ */
+int main() {
+    int x;
+    LNode *L = new LNode();
+    L = L->InitList(10);
+
+    // 删除表尾元素10
+    x = 10;
+    L->Print();
+    TrimRepeat2(L, x);
+    L->Print();
+
+    cout << "------------------------------" << endl;
+
+    // 删除表头元素1
+    x = 1;
+    L->Print();
+    TrimRepeat2(L, x);
+    L->Print();
+
+    cout << "------------------------------" << endl;
+
+    // 删除表中间元素5
+    x = 5;
+    L->Print();
+    TrimRepeat2(L, x);
+    L->Print();
+
+    system("pause");
+}