Last week I learned data structure about Linked List , in which include an algorithm for reversing a linked list . And in this chapter I will introduce this algorithm.

First considering a simple example . You is given a linked list of integers , and the question asks you to invert this linked list.

For example:

1
2
3
1->2->3->4->5->NULL

5->4->3->2->1->NULL

For iterating through this linked list and inverting it , you can declare three pointers (prev , curr, next), which represent the previous , current , next pointers. And in this way can you search this linked list and invert it iteratively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 ListNode* reverseList(ListNode* head) {

​ ListNode* prev=NULL;

​ ListNode* curr=head;

while(curr!=NULL)

​ {

​ ListNode* next=curr->next;

​ curr->next=prev;

​ prev=curr;

​ curr=next;

​ }

return prev;