【100題】第二十四 反轉鏈表

來源:互聯網
上載者:User

題目:建立一個鏈表,然後反轉一下

#include <iostream.h>#include <malloc.h>using namespace std;struct node{int data;node *next;};void insert(node *root,node *p){p->next=root->next;root->next=p;}node *create(int a[],int n){node *root=(node *)malloc(sizeof(node));root->data=a[0];root->next=NULL;for(int i=1;i<5;++i)    {   node *p = (node *)malloc(sizeof(node));   p->data=a[i];   p->next=NULL;   insert(root,p);    }return root;}node  *reverse(node *root){node *head=root;node *p;node *q;if(head)  p=head->next;    else        return head;while(p!=NULL){q=p->next;p->next=head;head=p;p=q;}return head;}int main(){node *root;int a[5]={2,3,4,5,6};root =create(a,5);node *temp1=root;for(int i=0;i<5;++i)    {   cout<<temp1->data<<endl;   temp1=temp1->next;    }        node *reverseHead=reverse(root);    cout<<"After reverse:"<<endl;node *temp2=reverseHead;    for(int i=0;i<5;++i)    {   cout<<temp2->data<<endl;   temp2=temp2->next;    }}

注意:建立鏈表的時候,切記一定要把節點node的所有元素都指明,例如node 有data、next 不要只初始化data而忘記p->next=NULL;

           如果忘記p->next=NULL;則在以後while(p)時候會停不下來

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.