|
@@ -0,0 +1,69 @@
|
|
|
+//
|
|
|
+// Created by tangs on 2018/9/29.
|
|
|
+//
|
|
|
+
|
|
|
+#include <iostream>
|
|
|
+
|
|
|
+using namespace std;
|
|
|
+
|
|
|
+typedef struct LNode {
|
|
|
+ int data;
|
|
|
+ LNode *next;
|
|
|
+} LNode;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 默认创建一个带头结点的单链表
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+LNode *InitLinkListWithHead(int length) {
|
|
|
+ LNode *L = new LNode();
|
|
|
+ L->data = 0;
|
|
|
+ L->next = NULL;
|
|
|
+
|
|
|
+ LNode *temp= L;
|
|
|
+ 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 *L) {
|
|
|
+ while (L != NULL) {
|
|
|
+ cout << L->data << " ";
|
|
|
+ L = L->next;
|
|
|
+ }
|
|
|
+ cout << endl;
|
|
|
+}
|
|
|
+
|
|
|
+void ReverseLinkList(LNode *&L) {
|
|
|
+ if (L == NULL || L->next == NULL) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ LNode *pre = NULL, *p = L->next, *rear = L->next->next;
|
|
|
+ while (rear != NULL) {
|
|
|
+ p->next = pre;
|
|
|
+ pre = p;
|
|
|
+ p = rear;
|
|
|
+ rear = rear->next;
|
|
|
+ }
|
|
|
+ p->next = pre;
|
|
|
+ L->next = p;
|
|
|
+ return;
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * 编写算法将带头结点的单链表就地逆置,所谓“就地”是指辅助空间复杂度为O(1)。
|
|
|
+ *
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+int main() {
|
|
|
+ LNode * L = InitLinkListWithHead(10);
|
|
|
+ Print(L);
|
|
|
+ ReverseLinkList(L);
|
|
|
+ Print(L);
|
|
|
+}
|