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