赞
踩
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int i,j; int length_of_a=0; int length_of_b=0; ListNode * process_node_A=headA; ListNode * process_node_B=headB; int find_flag=0; while(process_node_A!=nullptr) { length_of_a++; process_node_A=process_node_A->next; } while(process_node_B!=nullptr) { length_of_b++; process_node_B=process_node_B->next; } if(length_of_a<length_of_b) //保证a的长度是 长的 { //getIntersectionNode(headB,headA); // std::cout<<"反转 "<<std::endl; swap(length_of_a,length_of_b); swap(headA,headB); } //std::cout<<" length_of_a "<<length_of_a<<std::endl; // std::cout<<" length_of_b "<<length_of_b<<std::endl; //处理到相同起点 int move=length_of_a-length_of_b; // std::cout<<"move "<<move<<std::endl; // std::cout<<"move "<<move<<std::endl; for(i=1;i<=move;i++) headA=headA->next; //下面的长度是相同得了 process_node_A=headA; process_node_B=headB; while(process_node_A!=nullptr) { if(process_node_A==process_node_B) { // std::cout<<"结束方式1 "<<move<<std::endl; return process_node_A; find_flag=1; break; } else { process_node_A=process_node_A->next; process_node_B=process_node_B->next; } } return nullptr; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。