为什么在c++中,在双链表中添加节点的方法与单链表不同



这里有一个用于创建单链表的cpp程序:

#include <iostream> 

`using namespace std ;

//  starting with linked list 

class node {
public : 
int data ; 
node * next ; 

// constructer 
node ( int value){
data = value ;  
next = NULL ; 
}
};

int insertathead( node *&head , int data  ){
node*newhead ;
newhead = new node(data) ;  
newhead -> next = head ; 
head = newhead ; 
} 

void print(node*& head)
{
node* temp = head;
while (temp != NULL) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
int main () {  

node* node1 = NULL  ; 
insertathead(node1, 5 )  ;  
insertathead( node1 , 10) ;  
insertathead(node1 , 15 ) ;
insertathead( node1 , 20 ) ;
insertathead( node1 , 30 ) ; 
print ( node1 ) ;

return 0 ; 
}

这里有另一个用于创建双链表的cpp程序:

#include <iostream> 
using namespace std  ; 
class node {
public : 
int data; 
node*next ; 
node* prev ; 
// constructor 
node( int data )
{
this -> data = data ; 
next = NULL ; 
prev = NULL ; 
}
} ; 
void insertathead ( node*&head , int d  ) {
if ( head == NULL ) {
node*temp = new node(d) ; 
head = temp ; 
}
else 
{node*temp = new node(d) ; 
temp -> next = head ; 
head  -> prev = temp ; 
head  = temp ;} 
}
void print ( node**head ){
node*temp = *head ; 
while ( temp != NULL )
{
cout << temp -> data << " ->  " ; 

temp = temp -> next ; 
}
cout << "NULL " ; 
}
int main () { 
node* head = NULL ; 
insertathead( head , 5 ) ;
insertathead( head , 10) ;  
insertathead( head , 15 ) ;
insertathead(head , 20 ) ;
insertathead(head , 30 ) ; 
print ( &head ) ;
return 0 ; 
}

现在在单链表中的inserathead函数中,我不必创建特殊原因,如双链表中的if(head=NULL(,但在双链表中程序不会在不使用这种情况下打印列表,为什么

因为在一种情况下,head从未被取消引用,所以它是否为nullptr无关紧要。在双重链接的情况下,尽管你有:

head  -> prev = temp ; 

最新更新