双向链表尾插法
#include <iostream>
using namespace std;
typedef struct Node pNode;
struct Node{
int data;
pNode *prev,*next;
Node(const int& d):data(d),prev(NULL),next(NULL){}
};
/* 初始化链表,尾插法 */
pNode *insert(pNode *head/* or *&head */, int n){//*&head:指针的引用,此时**head本身不能改变,指向头节点;改变的是指向的指针*head.
pNode *p, *s;//p:游标 s:新申请节点
head = new Node(0);
head->next = NULL;//head的prev和next均指向NULL
head->prev = NULL;
p = head;//p指向head
for(int i = 0; i < n; i++){
s = new Node(i);
p->next = s;//游标p->next指向新申请节点
s->prev = p;//s前驱指针指向p
p = s;//游标p向后移动,p=s,p->next=s->next;
}
s->next = NULL;
return head;
}
void print(pNode *head){
while(head->next){
//cout <<"head->next: "<< head->next<<endl;
head = head->next;
cout << head->data << " ";
}
cout << endl;
}
int main(){
pNode *head, *new_head;
new_head = insert(head, 5);//初始化链表并赋值,返回尾节点last
print(new_head);
return 0;
}