题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <cstddef>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* ReverseList(ListNode* head) {
// write code here
//tem指针用于遍历目标链表,newafter与newtfront则用于创建新链表
//理想情况下只需要遍历一次链表就能得出新链表,而链表的线性就导致了用于创建的指针必须为2
//将tem当前指向的节点的数据用于让newtfront新建节点,新节点指向旧节点newafter
ListNode* tem=head,*newafter,*newtfront=NULL;
//指针移动至末尾
for (; tem!=NULL; tem=tem->next) {
newafter=newtfront;
newtfront=new ListNode(tem->val);
newtfront->next=newafter;
}
return newtfront;
}
};
查看19道真题和解析