简体   繁体   中英

Shift N Linked List Nodes To Front (C)

Here's a problem I'm having some trouble with in C. So, we have a function with two parameters:

  1. struct list ** ptrptr
  2. int K

K represents the number of Nodes that we have to shift from the end to the beginning of the list, like this:

在此处输入图片说明

I know how to shift one element, but I can't wrap my head around using tmps to solve with K nodes.

I would appreciate any suggestion. Here's the code for one node.

void Shift(node **head){
   node *prev;
   node *curr = *head;
   while(curr != NULL && curr->next != NULL) {
      prev = curr;
      curr = curr->next;
   }
   prev->next = NULL;
   curr->next = *head;
   *head = curr;

}

You can shift a complete chain of K nodes in a single "step". Suppose the list consists of N elements, that nmk is the node at position NK , and that e is the last node of the list. Then the code would be...

e->next = *head;
*head = nmk->next;
nmk->next = NULL;

The trick will now be to find node nmk , but I leave this up to you if you don't mind :-) And don't forget to check corner cases like empty lists, N==K , ....

// Shift the last N nodes of a linked list to the front of
// the list, preserving node order within those N nodes.
//
// Returns -1 if there are not enough nodes, -2 for invalid N,
// 0 otherwise
int shift(list_t **head, int n) {
    list_t *t1, *t2;
    int i;

    if ((head == NULL) || (*head == NULL))
        return -1;

    if (n <= 0)
        return -2;

    // move initial pointer ahead n steps
    t1 = *head;
    for (i = 0; i < n; i++) {
        t1 = t1->next;
        if (t1 == NULL) {
            return -1;
        }
    }

    t2 = *head;

    // t2 and t1 are now N nodes away from each other.
    // When t1 gets to the last node, t2 will point
    // to the node previous to the last N nodes.
    while (t1->next != NULL) {
        t1 = t1->next;
        t2 = t2->next;
    }

    // move the end nodes to the front of the list
    t1->next = *head;
    *head = t2->next;
    t2->next = NULL;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM