Inversion of the linked list

Question: Define a function that inputs the head node of a linked list, reverses the linked list, and returns the head node of the reversed linked list.

Since the pointer in the singly linked list is one-way, when the pointer of the current node points to its previous node, the node will be disconnected from the next node. At this time, we need to save the next node of the current node in advance. .

1 ListNode *reverse(ListNode* phead)
 2    {
 3       if (phead== NULL)
 4          {
 5              return NULL;
 6           }
 7        ListNode* pre= NULL; the previous node of the current node
 8        ListNode* pnode= phead;//current Node
 9        ListNode* pnext= NULL; the next node of the current node
 10       while (pnode!= NULL)
 11         {
 12            
13             pnext=pnode-> next;
 14            pnode->pnext= pre;
 15            pre=pnode;
16           pnode=pnext;
17        }
18        return pre;
19 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324867380&siteId=291194637