链表的使用方法
链表是我们日常编程中最常见到的一种数据结构,链表单个节点的定义如下所示
struct Node{
int Data; //最基本的数据元素
Node *next; //向下扩展的指针节点
};
下面我们通过链表的尾插法来学习使用链表
首先我们需要读取数据
//读取数据
Node* readData(int length){
Node* head = new Node;
Node* p = head;
int data;
for(int i=0;i<length;i++){
scanf("%d", &data);
p->Data = data;
p->next = new Node;
p = p->next;
}
p->next = NULL;
return head;
}
其次我们需要时刻获取链表的长度
//返回数据长度
int mDataLength(Node* p){
int length = 0;
while (p->next != NULL) {
p = p->next;
length++;
}
return length;
}
链表尾插的基本思路
//链表尾插法
Node* insertToTail(Node* Primary,Node* insertData){
Node* p = Primary;
int length = mDataLength(p);
for(int i=0;i<length-1;i++){
Primary = Primary->