面試訓練兩個鏈表的公用節點

來源:互聯網
上載者:User

有題目可以很容易的看出。

單鏈表 公用節點。必然最後一個節點相同,兩個鏈表成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;}

當然我以上的代碼 不是書中推薦的方法。

書中的方法是,既然兩個鏈表最後一個相等,長度不等,那麼我們把長的那一個走一部分節點 ,使兩個節點長度一樣長

然後再開始比不就行了嗎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.