有題目可以很容易的看出。
單鏈表 公用節點。必然最後一個節點相同,兩個鏈表成Y字形
感覺的話,需要從後往前找,那麼只有棧具有這個後進先出的性質。那麼c++的stl庫當然成為了首先選擇的結構了,為了節省時間吧,
用c實現一個花費的時間太多了。
代碼如下
#include "iostream"#include "stack"using namespace std;typedef struct Node{int data;struct Node *next;}Lnode;int main(){int num=10;int i=0,data;Lnode *head,*head1,*p,*q,*insert,*ret;head=NULL;head1=NULL;for(i=0;i<10;i++){scanf("%d",&data);if(head == NULL){head =(Lnode *)calloc(1,sizeof(Lnode));head->data=data;head->next=NULL;p=head;}else{q = (Lnode *)calloc(1,sizeof(Lnode));q->data=data;q->next=NULL;p->next=q;p=p->next;}if(i==5)insert=q;} p=head;while(p){printf("%d ",p->data);p=p->next;}putchar('\n');for(i=0;i<5;i++){scanf("%d",&data);if(head1 == NULL){head1 =(Lnode *)calloc(1,sizeof(Lnode));head1->data=data;head1->next=NULL;p=head1;}else{q = (Lnode *)calloc(1,sizeof(Lnode));q->data=data;q->next=NULL;p->next=q;p=p->next;}}p->next=insert;p=head1;while(p){printf("%d ",p->data);p=p->next;}putchar('\n');stack<Lnode *> myStack1;stack<Lnode *> myStack2;while(head){myStack1.push(head);head=head->next;}while(head1){myStack2.push(head1);head1=head1->next;}p=NULL;q=NULL;do{ret=p;p=(Lnode *)myStack1.top();q=(Lnode *)myStack2.top();myStack1.pop();myStack2.pop();}while(p==q);printf("%d ",ret->data);return 0;}
當然我以上的代碼 不是書中推薦的方法。
書中的方法是,既然兩個鏈表最後一個相等,長度不等,那麼我們把長的那一個走一部分節點 ,使兩個節點長度一樣長
然後再開始比不就行了嗎