Reverse linked List

Source: Internet
Author: User

Title: Enter a list, reverse the list, and output all the elements of the linked list.

Idea: This topic is a very classic list operation problem, involving a lot of linked list pointer operation, test code skills. Because it is a one-way list, if you follow the most common ideas and find the list of the last K nodes, there will be a lot of unnecessary traversal. Then you need to find a way to manipulate the pointer. Here is a better solution:

First you need to set 4 pointers, a phead to hold the inverted head node, Pnode represents the current node, Ppre represents the previous node of the current node, Pnext represents the next node of the current node.

Give me a chestnut: a->b->c->d->e->f->g->null

The current node points to a, the other node is temporarily null, and then pnext points to B, determines whether pnext is NULL, or null if it is to the end of the list, makes Phead point to Pnode, and then points pnext to Ppre. Then make Ppre point to Pnode,pnode point to Pnext. The loop is exited until the tail of the list exits.

Implementation code:

/*Public class ListNode {int val;    ListNode next = null;    ListNode (int val) {this.val = val; }}*/ Public classSolution { PublicListNode reverselist (ListNode head) {ListNode Pnode=Head; ListNode Ppre=NULL; ListNode Phead=NULL;  while(Pnode! =NULL) {ListNode Pnext=Pnode.next; if(Pnext = =NULL) {Phead=Pnode; } Pnode.next=Ppre; Ppre=Pnode; Pnode=Pnext; }        returnPhead; }}

Reverse linked List

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.