1、双指针法
cpp
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
ListNode* ReverseList(ListNode* pHead){
if(pHead == NULL)
return NULL;
ListNode* cur = pHead;
ListNode* pre =NULL;
while(cur != NULL)
{
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
2、递归写法
cpp
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return reverse(head,nullptr);
}
ListNode* reverse(ListNode* cur, ListNode* pre) {
if (cur == nullptr) return pre;
ListNode* temp = cur->next;
cur->next = pre;
return reverse(temp, cur); // 添加return语句以返回新链表的头结点
}
};