C++链表

复习到链表,写一个

这里一直困惑我的是&。。。本来认为&相当于*,,,,,,取内容,取地址。。。

但是写完了发现不是的,,,*&!=&(node *p);

他的意思只是说函数里我需要的是这个参数的引用,而不是副本。要的是目标本身。。

由于写中间插入删除要考虑前向指针,所以写个简单的,自己复习一下,,带了个没用的头结点的我给他赋值了0。

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 
 5 using namespace std;
 6 struct node{
 7 
 8 int data;
 9 node * next;
10 };
11 
12 void createlink(node* &head,int n)
13 {
14     //创建一个带空头节点的链表
15     head =new node;
16     head->data=0;
17     head->next=NULL;
18     node *ptr=head;
19     for(int i=0;i<n;i++)
20     {
21         node *p=new node;
22         p->data=(i+1);
23         p->next=NULL;
24         ptr->next=p;
25         ptr=ptr->next;
26     }
27     ptr->next=NULL;
28 
29 }
30 
31 void insertlinkend(node* &head,int data)
32 {
33 
34     node *p=head;
35     while(p->next!=NULL)
36     {
37         p=p->next;
38     }
39     node *a=new node;
40     a->data=data;
41     a->next=NULL;
42     p->next=a;
43 
44 }
45 
46 void deletelinkend(node* &head)
47 {//删除节点数据为data的节点
48     node *p=head;
49     node *po;
50     while(p->next!=NULL)
51     {
52         po=p;
53         p=p->next;
54     }
55     po->next=NULL;
56     delete(p);
57 
58 }
59 
60 void printlink(node* &head)
61 {
62     node *p=head;
63     p=p->next;
64     while(p->next!=NULL)
65     {
66         cout<<p->data<<endl;
67         p=p->next;
68     }
69     cout<<p->data;
70 }
71 
72 int main()
73 {
74     node *head=NULL;
75     createlink(head,8);
76     cout<<"insert one num:"<<endl;
77     int x;
78     cin>>x;
79     insertlinkend(head,x);
80     printlink(head);
81     cout<<"delete the last"<<endl;
82     deletelinkend(head);
83     printlink(head);
84     }
View Code
原文地址:https://www.cnblogs.com/8335IT/p/5862239.html