链表操作之快慢指针
来源:互联网 发布:网络安全法宣传周展板 编辑:程序博客网 时间:2024/05/17 06:25
使用包括链表的找环 判断链表相交 找倒数第几个节点。。。。。
代码:
#include<iostream>#include<assert.h>using namespace std;typedef struct node{ int data;int size;struct node*next;}node;typedef node* Lnode;void init(Lnode &head){head= new node;head->next=NULL;head->data=-1;head->size=0;}Lnode Buynode(int data){Lnode p=new node;p->next=NULL;p->data=data;return p;}void pushback(Lnode head,int data){assert(head != NULL); Lnode cur=head;while(cur->next != NULL){ cur=cur->next;} Lnode newnode=Buynode(data); cur->next=newnode; ++head->size;}void CreatCircle_Link(Lnode head,int pos){assert(head != NULL && head->size >1);int i=0;Lnode cur=head; while(i<pos){ cur=cur->next; ++i;}Lnode temp=cur;while(cur->next != NULL){cur=cur->next;}cur->next=temp;}void print(Lnode head){ assert(head != NULL); Lnode cur=head->next; while(NULL !=cur ) { cout<<cur->data; if(cur->next != NULL) { cout<<"->"; } cur=cur->next; } cout<<" size="<<head->size; cout<<"\n";}void reverse(Lnode head){assert(head != NULL);if(head->size <=1){return ;} Lnode pre=head->next;Lnode cur=pre->next;pre->next=NULL;Lnode nxt=NULL;while(cur != NULL){nxt= cur->next;cur->next=pre;pre=cur;cur=nxt;}head->next=pre;}void back_calc(Lnode head,int pos){assert(head != NULL&&head ->next != NULL && pos<=head->size);Lnode low=head;Lnode fast=head;int i=0;while(i<pos){fast=fast->next;++i;}while(fast!=NULL){ fast=fast->next; low=low->next;}cout<<low->data<<endl;}int isCircleLink(Lnode head){assert(head != NULL);if(head->next->next == NULL){return 0;} Lnode low =head; Lnode fast=head; while(fast->next!=NULL) { fast=fast->next->next; low=low->next; if(fast == low)//是环 { cout<<"是环\n"; for(low =head;low != fast;) { low=low->next;fast=fast->next; } cout<<"相交处的值: "<<low->data<<endl; int i=1;fast=fast->next; while(low !=fast) { fast=fast->next; ++i; } cout<<"环大小: " <<i<<endl; return 1; } } return 0;}int main(){ Lnode head; init(head); int i=0; while(i<5) { pushback(head,i+2);++i; } cout<<"print Link :\n"; print(head); cout<<"找倒数第2个数:\n"; back_calc(head,2); cout<<"翻转:\n"; reverse(head); print(head); CreatCircle_Link(head,2);isCircleLink(head);return 0;}
1 0
- 链表操作之快慢指针
- 链表追赶之快慢指针
- 链表之快慢指针续
- 快慢链表和快慢指针
- 链表快慢指针应用
- 数据结构之快慢指针查找链表中间结点
- 快慢指针在链表的应用
- 快慢指针在链表的应用
- 快慢指针,链表的排序
- 快慢指针和链表原地反转
- 快慢指针在链表中的应用
- 链表的快慢指针:查找中点
- 快慢指针在链表的应用
- 链表的快慢指针:查找中点
- 快慢指针 —— 链表中点
- LintCode 带环链表(快慢指针法)
- 链表面试题之快慢指针问题(一) 查找链表中间节点
- 运用快慢指针判断链表是否有环
- xml getResponseHeaders()函数
- (原)新花生壳内网版2.3 + Tomcat7 搭建自己的网站
- 月薪3万的程序员都避开了哪些坑
- hmac
- NDK编译Android字符界面的可执行程序
- 链表操作之快慢指针
- CentOS运行与控制后台进程的方法
- bzoj2151 种树
- Android之Application
- vector的reserve()和resize()
- 基于Android的CPU+GPU的异构编程开发,目前主要有以下几种平台
- 150. Evaluate Reverse Polish Notation
- Lintcode 将二叉查找树转换成双链表
- .xml解析和序列化