部分翻转链表

    科技2025-10-14  2

    每k个翻转一次

    这次算彻底搞懂了翻转链表的各种写法了,花费了大概2个小时才想明白 对比静态链表的部分翻转,这个是技术活,而静态链表是表示后排序串成一个挨着的数组,然后再按照下标输出,毫无水平的感觉只是条件复杂点写起来感觉难一些 静态链表的传送门

    list reverse(list l,int k) { if (k <= 1||l==NULL) { return l; } else { int allcount = 0; list cur = l, head = l, rear = l; list temp = NULL; while (cur) { int count = 0; list pre = NULL; while (cur != NULL && count < k) { temp = cur->next; cur->next = pre; pre = cur; cur = temp; count++; } allcount++; if (allcount == 1) { l = pre; head = temp; } else { rear->next = pre; rear = head; head = temp; } } } return l; }
    翻转链表中第m个到n个
    list reverse(list l, int m, int n) { list pre = l; for (int i = 1; i < m-1; i++) { pre = pre->next; } int count = 0; list cur = pre->next; list curr = cur; list temp = NULL; list pree = NULL; while (count < n - m + 1) { temp = cur->next; cur->next = pree; pree = cur; cur = temp; count++; } pre->next = pree; curr->next = temp; return l; }

    附上测试代码:

    #include<iostream> using namespace std; const int maxn = 100; struct node { int data; node* next; }; typedef node* list; list insert(list a,int x) { if (a == NULL) { list temp = new node; temp->data = x; temp->next = a; a = temp; } else { list aa = a; while (aa->next != NULL) { aa = aa->next; } list temp = new node; temp->data = x; temp->next = NULL; aa->next = temp; } return a; } //每k个翻转一次 list reverse(list l,int k) { if (k <= 1||l==NULL) { return l; } else { int allcount = 0; list cur = l, head = l, rear = l; list temp = NULL; while (cur) { int count = 0; list pre = NULL; while (cur != NULL && count < k) { temp = cur->next; cur->next = pre; pre = cur; cur = temp; count++; } allcount++; if (allcount == 1) { l = pre; head = temp; } else { rear->next = pre; rear = head; head = temp; } } } return l; } //翻转链表中第m个到n个。 list reverse(list l, int m, int n) { list pre = l; for (int i = 1; i < m-1; i++) { pre = pre->next; } int count = 0; list cur = pre->next; list curr = cur; list temp = NULL; list pree = NULL; while (count < n - m + 1) { temp = cur->next; cur->next = pree; pree = cur; cur = temp; count++; } pre->next = pree; curr->next = temp; return l; } void print(list l) { while (l != NULL) { cout << l->data << "->"; l = l->next; } cout << endl; } int main() { list l = NULL; for (int i = 1; i <=10; i++) { l = insert(l, i); } print(l); /*int k, n = 100; cin >> k; l=reverse(l, k, n); print(l);*/ l=reverse(l,4, 6); print(l); }
    Processed: 0.015, SQL: 8