Reverse Linked List 题解
题目来源:https://leetcode.com/problems/reverse-linked-list/description/
Description
Reverse a singly linked list.
Solution
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head -> next == NULL)
return head;
ListNode *preNode = head,
*curNode = preNode -> next,
*nextNode = curNode -> next;
while (true) {
curNode -> next = preNode;
if (nextNode == NULL)
break;
preNode = curNode;
curNode = nextNode;
nextNode = nextNode -> next;
}
head -> next = NULL;
return curNode;
}
};
解题描述
这道题是经典的链表反转。使用的解法是使用preNode
、curNode
和nextNode
三个相邻的指针,每次将curNode
指向preNode
,然后三个指针都向后移,最后将head
的下一节点置空即可。