链表分段反转
来源:互联网 发布:软件图标显示异常 编辑:程序博客网 时间:2024/05/19 17:58
链表翻转。给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,则翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6,用程序实现
#include<stdio.h>#include<stdlib.h>#include<iostream>using namespace std;struct Node{int data;Node *next;};void reverse(Node *head,Node *end){if(head==NULL||end==NULL) return;Node *pre=NULL,*cur=head,*stop=end->next;while(cur!=stop){Node* nxt=cur->next;cur->next=pre;pre=cur;cur=nxt;}}Node* reverseAll(Node *head,int k){if(head==NULL||k<=0) return NULL;Node *cur=head;for(int i=0;i<k-1;i++){cur=cur->next;if(cur==NULL) break;}if(cur==NULL) return head;Node* begin=cur->next,*end=begin;Node* pre=head;reverse(head,cur);while(begin!=NULL){for(int i=0;i<k-1;i++){end=end->next;if(end==NULL) break;}if(end==NULL){pre->next=begin;break;}else{Node *nextbegin=end->next;reverse(begin,end);pre->next=end;pre=begin;begin=end=nextbegin;}}return cur;}int main(){int a[]={1,2,3,4,5,6,7,8,9,10,11,12};Node* nd[12];for(int i=0;i<12;i++){nd[i]=new Node;nd[i]->next=NULL;nd[i]->data=a[i];}for(int i=0;i<11;i++){nd[i]->next=nd[i+1];}Node *tmp=reverseAll(nd[0],4);for(;tmp!=NULL;tmp=tmp->next){cout<<tmp->data<<endl;}system("pause");return 0;}
- 链表分段反转
- 尾插法、头插法创建链表、链表反转、链表分段反转、查找链表倒数第k个元素,查找链表中间元素
- 链表分段翻转
- 链表反转
- 反转链表
- 单向链表反转
- 链表反转:
- 链表的反转
- 链表反转
- 反转单向链表
- 链表反转
- 单向链表反转
- 单向链表反转
- 链表的反转
- 链表反转
- 反转链表
- 链表反转
- 链表反转
- poj.1988并查集-路径压缩、更新结点(偏移量)
- vi的高级使用
- 课下总结
- 验证文本框只能输入数字
- merge into多表关联更新
- 链表分段反转
- 常用正则表达式
- HUT_ACM #1 D Matrix Multiplication(ZOJ-2316)
- 用java生成html文件
- Mysql编码设置
- JAVA获取CLASSPATH路径
- 图片与文字对齐css样式
- TCP/IP socket编程
- C++学习笔记(1)void*指针