Title description:
Define a function, input the head node of a linked list, reverse the linked list and output the head node of the reversed linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Thinking analysis:
It is the easiest way to traverse each node in the linked list, then use the head interpolation method to insert into the new linked list, and finally return to the new linked list
Key code (that is, change the shape of the head insertion method) :
head3 = head->next; //First save the linked list x that needs to be reversed from the next node y
head ->next = head1; //The next node of the node becomes a new linked list z
head1 = head; / /z replaces the position of the new linked list again
head = head3; //Re-assign the saved y to the linked list that needs to be reversed for the next cycle
Code:
/**
* 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 *head1 = NULL;
ListNode *head3 = NULL;
while(head)
{
head3 = head->next;
head ->next = head1;
head1= head;
head = head3;
}
return head1;
}
};