Reverse a singly linked list.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prior = NULL, *node = head;
while (node != NULL) {
auto next = node->next;
node->next = prior;
prior = node;
node = next;
}
return prior;
}
};
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode node = head;
if (node == null || node.next == null) {
return node;
}
ListNode next = node.next;
while (node != null && next != null) {
ListNode newNext = next.next;
next.next = node;
node = next;
next = newNext;
}
head.next = null;
return node;
}
public ListNode reverseList(ListNode head) {
ListNode node = head;
if (node == null || node.next == null) {
return node;
}
ListNode prior = null;
while (node != null) {
ListNode next = node.next;
node.next = prior;
prior = node;
node = next;
}
return prior;
}
}