Book notes-Interview Questions 16: reverse linked list

Source: Internet
Author: User

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

Linked List node definition:

struct ListNode{int m_nValue ;ListNode* m_pNext ;} ;

At the beginning, I first thought about recursive solutions:

ListNode * ReverseLinkedList (ListNode * pListHead) {if (NULL = pListHead) {return NULL;} else if (NULL = pListHead-> m_pNext) // only one node {return pListHead;} ListNode * pNewHead = ReverseLinkedListCore (pListHead, NULL); return pNewHead;} ListNode * ReverseLinkedListCore (ListNode * pCurNode, ListNode * pPrevNode) {if (NULL = pCurNode) {return NULL;} if (NULL = pCurNode-> m_pNext) // to the last node {pCurNode-> m_pNext = pPrevNode; // start to reverse the linked list return pCurNode; // The Last node is the new header node} else {ListNode * pNewHead = ReverseLinkedListCore (pCurNode-> m_pNext, pCurNode ); pCurNode-> m_pNext = pPrevNode; return pNewHead ;}}

The solution in the book is non-recursive, more direct and concise:

ListNode * ReverseList (ListNode * pHead) {ListNode * pReversedHead = NULL; ListNode * pNode = pHead; ListNode * pPrev = NULL; while (pNode! = NULL) {ListNode * pNext = pNode-> m_pNext; if (pNext = NULL) // there is only one node {pReversedHead = pNode;} pNode-> m_pNext = pPrev; pPrev = pNode; pNode = pNext;} return pReversedHead ;}



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.