书上的题目,带头链表&不带头链表
不带头链表为空时,判断:head==NULL;
带头链表为空是,判断head->next=NULL;
但对于链表的插入、删除会有不同,不带头链表对于头节点需要单独处理,而对于带头链表则不需要
1 #include <iostream> 2 using namespace std; 3 typedef struct node 4 { 5 int date; 6 struct node* next; 7 }*linklist,listnode; 8 linklist initlist(linklist head) 9 { 10 head=new listnode; 11 head->next=NULL; 12 return head; 13 } 14 void input(linklist head,int n) 15 { 16 linklist tail=NULL,temp=NULL; 17 while(n--) 18 { 19 if(tail==NULL) 20 { 21 cin>>head->date; 22 tail=head; 23 } 24 else 25 { 26 temp=new listnode; 27 cin>>temp->date; 28 tail->next=temp; 29 tail=temp; 30 tail->next=NULL; 31 } 32 } 33 tail->next=head; 34 } 35 linklist bin(linklist head1,linklist head2) 36 { 37 linklist p=head1,tail; 38 while(p->next!=head1) 39 p=p->next; 40 tail=p; 41 tail->next=head2; 42 p=head2; 43 while(p->next!=head2) 44 p=p->next; 45 p->next=head1; 46 return p; 47 } 48 void outputlist(linklist head) 49 { 50 linklist p=head; 51 while(p!=NULL) 52 { 53 cout<<p->date<<‘ ‘; 54 p=p->next; 55 } 56 } 57 int main() 58 { 59 linklist head1,head2,tail=NULL,p; 60 head1=initlist(head1); 61 head2=initlist(head2); 62 input(head1,5); 63 input(head2,5); 64 tail=bin(head1,head2); 65 p=head1; 66 while(p!=tail) 67 { 68 cout<<p->date<<‘ ‘; 69 p=p->next; 70 } 71 cout<<tail->date; 72 return 0; 73 }
时间: 2024-10-03 16:31:49