B Basak - 1 year ago 64

C Question

I want to reverse the last 5 nodes in a linked list as follows:

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

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

I have written the following code to perform the above task but my reverse() function is not working.

`#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);

}

Is there any error in my logic in the reverse() function? I tried the dry run on paper and it should have worked but it isn't working. Please point out the mistake that I made or even better suggest some alternative code to solve this problem.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The problem is in the line:

```
next = next->next;
```

in this part of the code:

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

In the last element, when current becomes the last node current->next is NULL and you try to get next->next->next which gives segmentation fault. You need to change the above line simply by adding an if statement:

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

I tried with your given input and it works!!

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**