iterative C#


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode ReverseKGroup(ListNode head, int k) {
            List<ListNode> kList=new List<ListNode>();
            int couter=0;
            while(head!=null)
            {
                if(couter==0)
                    kList.Add(head);
                couter++;
                var temp=head.next;
                if(couter==k)
                {
                    couter=0;
                    head.next=null;
                }
                head=temp;
            }
            if(kList.Count==0)
                return head;
            ListNode dummy=new ListNode(0),runner=dummy;
            for(int i=0;i<kList.Count-1;i++)
            {
                var temp=kList[i];
                runner.next=reverseList(kList[i]);
                runner=temp;
            }
            if(couter>0)
                runner.next=kList[kList.Count-1];
            else
                runner.next=reverseList(kList[kList.Count-1]);
            return dummy.next;
        }
        
        
        private ListNode reverseList(ListNode head)
        {
            ListNode pre=null;
            while(head!=null)
            {
                ListNode temp=head.next;
                head.next=pre;
                pre=head;
                head=temp;
            }
            return pre;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.