Reverse linked list-finger offer-16

Source: Internet
Author: User

title : Define a function, enter the head node of a linked list, reverse the list and output the head node of the inverted list.


Analysis:

Header-by-head interpolation for reversal

Set 3 pointers: Head node, prev previous node, cur next node


Note: The linked list is empty, or only one node is in the case!


Code:

#include <iostream>using namespace Std;struct listnode{int val; ListNode *next; ListNode (int x): Val (x), Next (nullptr) {}};class solution{public:listnode* reverselist (listnode* phead) {if (Phead = = nullptr | | Phead->next = = nullptr) return phead; ListNode Dummy ( -1);d ummy.next = Phead; ListNode *head = &dummy; listnode* prev = head->next; listnode* cur = prev->next;do{prev->next = Cur->next;cur->next = Head->next;head->next = Cur;cur = prev ->next;} while (cur! = nullptr); return dummy.next;};


Sword refers to the code on the offer book:

Listnode* reverlist (listnode* phead) {    listnode* preversehead =  null;    listnode* pnode = phead;    listnode*  pprev = null;        while (PNode != NULL)     {        ListNode* pNext =  pnode->m_next;                 if (pnext == null)              preversehead = pnode;                   pNode->m_next = pPrev;                   pPrev = pNode;          pnode = pnext;    }        return  preversehead; }

Welcome to discuss the exchange!

This article is from the "pin-soil" blog, please be sure to keep this source http://3240611.blog.51cto.com/3230611/1617528

Reverse linked list-finger offer-16

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.