Linked List----press K nodes to reverse the list.

Source: Internet
Author: User

Title: Reverse the list by a group of K nodes.


Ideas:

By using the reverse of the inverted link list, the linked list is cycled, and the pointer continues to move forward when the count length k is not applied . When the count length reaches K, the group's endpoints First and node are passed in as parameters to the rollover function reverse and then re-stitched into the original linked list. Until the end of the list is reached.


The code is as follows:

/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * Next = Null *} *} */public class Solution {public ListNode Reversekgroup (ListNode head, int k) {if (head = = null| | Head.next = = null| |                K<=1) return head;                ListNode Node=head; ListNode helper=new listnode (0);//Create an auxiliary head node; helper.next=head;//when the k> length of list returns to the original list; ListNode last         group=helper;//records the tail node of a set of nodes; ListNode nextgroup=head;//assists in recording the first node of the next set of nodes; ListNode first=nextgroup;//records the first node of the next set of nodes;        int count=1;                while (Node!=null) {if (count<k) {count++;            Node=node.next;                }else//count = = k;                {nextgroup=node.next;                Lastgroup.next=reverse (First,node);                Lastgroup=first;        First.next=nextgroup;        First=nextgroup;                                Node=first;            Count=1;            }} return helper.next;        }//String reversal general method, public ListNode reverse (listnode head,listnode tail) {ListNode pre=head;        ListNode Cur=head.next;        ListNode Ne=null;            while (Pre!=tail) {ne=cur.next;            Cur.next=pre;            Pre=cur;        Cur=ne;        } head.next=null;        Head=pre;    return head; }}


Linked List----press K nodes to reverse the 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.