单向链表的建立与遍历
typedef struct Snode
{
int data;
Snode *next;
}Snode,*PSnode;
void CreateList(PSnode &head)
{
int n;
PSnode p,q;
head=new Snode;
head->data = 0;
head->next = NULL;//Initial node
q = head; //负责衔接链表的 尾指针
cout << "how many number?\n n=";
cin >> n;
while (n > 0)
{
p = new Snode; //开辟新空间
p->next = NULL;
cin >> p->data;
q->next = p; //衔接链表
q = p; //尾指针传递
--n;
}
}
void Print(PSnode&head)
{
PSnode p = head->next;
while (p)
{
cout << p->data << endl;
p = p->next;
}
}
本文介绍了一种使用C++实现单向链表的方法,包括链表节点的定义、链表的创建过程及链表元素的遍历打印。通过具体代码示例展示了如何动态分配内存创建链表节点,并通过尾指针进行节点间的链接。
1422

被折叠的 条评论
为什么被折叠?



