剑指offer常用链表操作

来源:互联网 发布:只看数据伯德被低估 编辑:程序博客网 时间:2024/06/06 12:46

   剑指offer中有很多的关于链表的操作,现总结如下:(对于单向链表,由于不能回溯,故比双向指针要更稍微复杂些)

#include <iostream>#include <string>using namespace std;//单链表的数据结构struct List_node{char data;List_node *next;};class List_solution{public://创建链表List_node* create_List(){List_node *list_head=new List_node;list_head->data='#';list_head->next=NULL;char data;List_node *tem=list_head;int i=1;while(true){cout<<"请输入下第"<<i<<"个结点的数据值:"<<endl;cin>>data;if(data=='#')break;else{List_node* p=new List_node;p->data=data;tem->next=p;p->next=NULL;tem=p;}i++;}return list_head;}void print_List(List_node * list_head){while(list_head->next!=nullptr){cout<<list_head->next->data<<"-->";list_head=list_head->next;}cout<<"NULL"<<endl;}//翻转链表,由于是单向链表,不能往前回溯,有不能让链表断裂,所以要维护三个指针List_node* reverse(List_node *listhead){if(listhead==NULL)return NULL;List_node* pre=NULL;List_node* pnext=NULL;List_node* pcurrent=listhead->next; //开始指向第一个元素while(pcurrent!=NULL){pnext=pcurrent->next; //保存当前结点的下一个元素pcurrent->next=pre; //把当前的结点的下一个结点指向上一个结点,实现反向pre=pcurrent;   //把上一个结点设为当前结点pcurrent=pnext;  //把当前结点指向下一个结点}listhead->next=pre;return listhead;}//合并两个排序好的链表List_node* merge(List_node* listhead1,List_node* listhead2){List_node* p1=listhead1->next;List_node* p2=listhead2->next;//首先考虑特殊情况if(p1==nullptr)   //为空return listhead2;else if(p2==nullptr)return listhead1;List_node* tem=listhead1;while(p1!=nullptr&&p2!=nullptr){if(p1->data<p2->data)  //listhead1的值比较小,一直后退直到大于listhead2结点的值{while(p1!=nullptr&&p1->data<p2->data){tem->next=p1;tem=tem->next;p1=p1->next;}}else if(p2->data<p1->data)//listhead2的值比较小{while(p2!=nullptr&&p2->data<p1->data){tem->next=p2;tem=tem->next;p2=p2->next;}}}tem->next=(p1==nullptr)?p2:p1;     //最后肯定有一个先为空,直接把还非为空的指针接在后面return listhead1;}};int _tmain(int argc, _TCHAR* argv[]){List_solution list;List_node *list1=list.create_List();List_node *list2=list.create_List();list.print_List(list.merge(list1,list2));//List_node *head=list.create_List();//list.print_List(head);//list.print_List(list.reverse(head));return 0;}
总结:在链表的操作中往往会涉及到很多的指针操作,所以要特别注意出现空指针的情况,还有什么时候到达边界,防止可能因为一些特殊的输入导致程序崩溃。

0 0