main.cpp:
#include <iostream>
#include "node.h"
using namespace std;
void inverted(node* &head,int latter_num,node* &temp);
int main()
{
//head为空 表头节点 指向第一个节点。注意一定要用new。node* head;←这样是不对的
node* head = new node();
node* curr = new node();
//temp不可以放在inverted函数里new 这样的话每调用一次都会new一个新的出来 最后给head赋值的时候赋的是空值
node* temp = new node();
curr = head;
for(int i = 0;i < 10;i++)
{
cout<<"请输入第"<<(i+1)<<"个数据"<<endl;
int data;
cin>>data;
node* newNode = new node(data);
curr -> next = newNode;
curr = curr -> next;
}
cout<<endl;
for(int i=10;i>0;i--)
{
//head 对应node* &
inverted(head,i,temp);
}
curr = head;
for(int i = 0;i<10;i++)
{
curr = curr->next;
cout<<curr->nodeValue<<endl;
}
}
void inverted(node* &head,int latter_num,node* &temp)
{
node* prev = new node();
node* curr = new node();
curr = head->next;
prev = head;
for(int i = 0;i < latter_num-1;i++)
{
curr = curr->next;
prev = prev->next;
}
curr->next = prev;
if(latter_num == 10)
{
// node *temp = new node();
temp->next = curr;
}
else if(latter_num == 1)
{
head = temp;
}
}
node.h:
#include<cstdlib>
class node{
public:
node* next;
int nodeValue;
node():next(NULL)
{}
node(const int& item,node* nextNode = NULL):nodeValue(item),next(nextNode)
{}
};
本来想建成模板链的,遇到了一些错误 :
‘NULL’ wasn’t declared in this scope
需要头文件 <stddef.h> 或 <stdlib.h> 或 <cstdlib>
Missing template arguments before “alist”
代码:linkedlist alist()改为linkedlist<int> alist()
定义类对象时也需要用模板
invalid use of template-name 'linkedlist' without an argument list
linkedlist::linkedlist(node<T>* first,int size)
改为linkedlist<T>::linkedlist(node<T>* first,int size)
'T' was not declared in this scope
template<class T>
void f(){
}<---- 这之后T就不能用了
template<class T> <--- 这个T和上面的T不是一个
undefined reference to `linkedlist<int>::linkedlist(node<int>*, int)'
g++不支持模板类的分离编译,因此模板的实现最好都些在.h文件中,否则将出现undefined reference to XXXX 的错误。
还有可能和宏定义重复定义有关 比如说ifndef巴拉巴拉
将linkedlist变为类后可以不这么写:
node<int> *first = new node<int>();
linkedlist<int> alinked(first,10);
因为这样写的本意是想通过第一个节点去辨识一条链 但其实根本不需要这样 因为把linkedlist也作为类之后它本身的对象就可以区分不同的链(由于print的时候要遍历 可以在linkedlist中添加一个数据成员 就是head 这样就不用传参数了)
一点疑问:
首先定义一个指向Head的指针q;
然后不断重复以下三个步骤完成单链表的构造:
①用new申请一个LinkNode的空间返回指针p,并输入数据元素;
②q->next=p,将q指针对应结点的后继修改为p;
③q=q->next,将指针指向其直接后继,这样一个结点就被链接进了链表之中。
可是为什么这样就可以完成单链表的构造?为什么不是head的next依旧是NULL 只是以q为head建了一条链呢