问题:这个是牛课网上的题,其中声明的是vector类型
结果:递归方法
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) { //vector 容器
vector<int> vec;
printListFromTailToHead(head,vec);
return vec;
}
void printListFromTailToHead(struct ListNode* head,vector<int> &vec)
{
if(head!=nullptr)
{
if(head->next!=nullptr)
{
printListFromTailToHead(head->next,vec);//递归
}
vec.push_back(head->val);
}
}
};
编程1:
向量 vector 是一种对象实体, 能够容纳许多其他类型相同的元素, 因此又被称为容器。 与string相同, vector 同属于STL(Standard Template Library, 标准模板库)中的一种自定义的数据类型, 可以广义上认为是数组的增强版。
1.首先先声明一个链表vec
2.调用构造函数实现反转 (通过在新链表尾部添加元素)
3.构造函数 :
如果头指针不为空,递归循环head的下一个元素,vec.push_back(head->val)函数是指在vec
的尾部加入元素head->val ,head->val是指该head指针所对应链表中的数值。
4.返回新链表
这个是在leetcode中的反转链表的题目,其中,声明的是ListNode链表类型的。
题目:
答案:
迭代方法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode*pre=nullptr,*cur=head,*r=nullptr;
while(cur!=nullptr){ //其实就是将前后指针反转,r只是一个中间变量,临时存放下一个节点
r=cur->next;
cur->next=pre;
pre=cur;
cur=r;
}
return pre;
}
};
递归方法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode *new_head = reverseList(head->next);//新建一个链表用来存反转后的链表
head->next->next = head; //head->next即head的下一个节点的下一个节点
head->next = NULL;
return new_head;
}
};