Saturday, December 19, 2015

Reversing Parts of a LinkedList

Initial LinkedList: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 

Input: count = 3
Output: 3, 2, 1, 6, 5, 4, 9, 8, 7, 0, 

Input: count = 4
Output: 4, 3, 2, 1, 8, 7, 6, 5, 0, 9,

Input: count = 7
Output: 7, 6, 5, 4, 3, 2, 1, 0, 9, 8,


    public void compute(int count)    {
        LinkedList L = this;
        int i=0;
        StringBuffer sb = new StringBuffer();
        Stack<Integer> S = new Stack<Integer>();
        while(L!=null)    {
            if(i<count)    {
                S.push(L.data);
                L=L.next;
                i++;
            }    else    {
                while(!S.isEmpty())
                    sb.append(S.pop()).append(", ");
                i=0;
            }
        }
        while(!S.isEmpty())
            sb.append(S.pop()).append(", ");
        System.out.println(sb.toString());
    }

No comments:

Post a Comment

UA-39217154-2