原地算法
递归
ListNode* head1;
ListNode* reverseList(ListNode* head) {
dfs(head, NULL);
return head1;
}
void dfs(ListNode* cur, ListNode* pre){
if(cur == NULL){
head1 = pre;
return;
}
ListNode* tmp = cur->next;
cur->next = pre;
dfs(tmp, cur);
}
循环
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL; //前指针节点
ListNode* curr = head; //当前指针节点
//每次循环,都将当前节点指向它前面的节点,然后当前节点和前节点后移
while (curr != NULL) {
ListNode* nextTemp = curr->next; //临时节点,暂存当前节点的下一节点,用于后移
curr->next = prev; //将当前节点指向它前面的节点
prev = curr; //前指针后移
curr = nextTemp; //当前指针后移
}
return prev;