Ejemplo n.º 1
0
struct LNode* ReverseGroup(struct LNode* root,int n){

struct LNode* current=root;
struct LNode* prev=NULL;
struct LNode* next;
struct LNode* rootHolder=root;
int count=0;
while(current && count<n){
next=current->next;
current->next=prev;
prev=current;
current=next;
count++;
}

if(current){
rootHolder->next=current;
count=0;
while(current && count<n-1 ){
current=current->next;
count++;
}
if(current->next){
current->next=ReverseGroup(current->next,n);
}
}
return prev;
}
ListNode* Reverse(ListNode* pHead, unsigned int k)
{
    if(pHead == NULL || k <= 1)
        return pHead;

    ListNode* pReversedHead = NULL;
    ListNode* pNode1 = pHead;
    ListNode* pPrev = NULL;
    while(pNode1 != NULL)
    {
        // find k nodes within a group
        ListNode* pNode2 = pNode1;
        ListNode* pNext = NULL;
        for(unsigned int i = 1; pNode2->m_pNext != NULL && i < k; ++i)
            pNode2 = pNode2->m_pNext;

        pNext = pNode2->m_pNext;

        // reverse nodes within a group
        ReverseGroup(pNode1, pNode2);

        // connect groups together
        if(pReversedHead == NULL)
            pReversedHead = pNode2;

        if(pPrev != NULL)
            pPrev->m_pNext = pNode2;
        pPrev = pNode1;
        pNode1 = pNext;
    }

    return pReversedHead;
}
Ejemplo n.º 3
0
int main(){
int i;
int data;
struct HNode* root=(struct HNode* )malloc(sizeof(struct HNode));
root->count=0;
root->next=NULL;
struct HNode* root1=(struct HNode* )malloc(sizeof(struct HNode));
root1->count=0;
root1->next=NULL;
struct HNode* root2=(struct HNode* )malloc(sizeof(struct HNode));
root2->count=0;
root2->next=NULL;
int n;
printf("\nEnter data for first lsit \n");
getch();
for(i=0;i<6;i++){
printf("\nenter data for %dth node : ",i);
scanf("%d",&data);
Insert(root,data);
}

printf("\n%d Nodes inserted...",i);
getch();

printf("\nEnter to traverse..\n\n");
getch();
Traverse(root);
getch();
printf("\nEnter to reverse in group \nEnter group length : ");
scanf("%d",&n);
root->next=ReverseGroup(root->next,n);

getch();
Traverse(root);
return 0;
}