反转链接列表中的最后5个节点

时间:2016-09-10 06:01:25

标签: c data-structures

我想反转链表中的最后5个节点,如下所示:

Input: 2->4->6->8->10->12->14->16->NULL
Output: 2->4->6->16->14->12->10->8->NULL

我编写了以下代码来执行上述任务,但我的reverse()函数无效。

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

int n;

void insert(struct node **headref, int data) {
    struct node *new_node;
    new_node = malloc(sizeof(struct node));
    new_node->data = data;
    new_node->next = *headref;
    *headref = new_node;
}

struct node* create() {
    struct node dummy;
    struct node *new_node = &dummy;
    dummy.next = NULL;
    int i,num;
    printf("Enter The Number Of Data: ");
    scanf("%d", &n);
    for(i = 1; i <= n; i++) {
        printf("Enter Data %d: ", i);
        scanf("%d", &num);
        insert(&(new_node->next), num);
        new_node = new_node->next;
    }
    return dummy.next;
}

void display(struct node *head) {
    struct node *current;
    for(current = head; current != NULL; current = current->next) {
        printf("%d  ", current->data);
    }
    printf("\n");
}

void reverse(struct node *head) {
    struct node *current, *next, *prev, *temp;
    current = head;
    next = current->next;
    prev = NULL;
    int i;
    for(i = 0; i < n-5; i++) {
        temp = current;
        current = next;
        next = next->next;
    }

    while(current != NULL) {
        current->next = prev;
        prev = current;
        current = next;
        next = next->next;
    }

    temp->next = prev;
}

int main() {
    struct node *start = create();
    display(start);
    reverse(start);
    display(start);
}

reverse()函数中的逻辑是否有错误?我尝试在纸上干运行它本来应该有效,但它不起作用。请指出我所犯的错误,甚至更好地建议一些替代代码来解决这个问题。

1 个答案:

答案 0 :(得分:3)

问题在于:

next = next->next;

在这部分代码中:

while(current != NULL) {
        current->next = prev;
        prev = current;
        current = next;
        next = next->next;
    }

在最后一个元素中,当电流变为最后一个节点current-&gt; next为NULL并且您尝试获得next-&gt; next-&gt; next,这会产生分段错误。 您只需添加if语句即可更改上述行:

 while(current != NULL) {
        current->next = prev;
        prev = current;
        current = next;
        if (next!=NULL) next = next->next;
    }

我尝试了你给定的输入,它可以工作!!