php做用户注册网站,开网站做外贸,建设网上银行登录,上海著名的建筑设计公司题目 给定一个单链表的头结点pHead(该头节点是有值的#xff0c;比如在下图#xff0c;它的val是1)#xff0c;长度为n#xff0c;反转该链表后#xff0c;返回新链表的表头。
数据范围#xff1a;0≤n≤1000 要求#xff1a;空间复杂度 O(1) #xff0c;时间复杂度 O…题目 给定一个单链表的头结点pHead(该头节点是有值的比如在下图它的val是1)长度为n反转该链表后返回新链表的表头。
数据范围0≤n≤1000 要求空间复杂度 O(1) 时间复杂度 O(n) 。
如当输入链表{1,2,3}时 经反转后原链表变为{3,2,1}所以对应的输出为{3,2,1}。 以上转换过程如下图所示 示例1
输入{1,2,3}
返回值{3,2,1}示例2
输入{}
返回值{}
说明
空链表则输出空思路 1、定义pre指向null
2、定义cur指向head
3、定义temp指向cur-next
4、将cur-next指向pre
5、重复34步骤将pre和cur不断后移直到cur等于null循环结束返回pre指针。
解答代码 /*** struct ListNode {* int val;* struct ListNode *next;* ListNode(int x) : val(x), next(nullptr) {}* };*/
class Solution {
public:/*** param head ListNode类 * return ListNode类*/ListNode* ReverseList(ListNode* head) {// write code hereif (head nullptr) {return nullptr;}ListNode* pre nullptr;auto cur head;while (cur ! nullptr) {auto tmp cur-next;cur-next pre;pre cur;cur tmp;}return pre;}
};