目录
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int data;
struct node_s *next;
} node_t;
node_t *create_node(int data) {
node_t *new_node = malloc(sizeof(node_t));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
node_t *append(node_t *head, int data) {
node_t* new_node = create_node(data);
if (NULL == head) {
head = new_node;
} else {
node_t *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
return head;
}
node_t *reverse(node_t *head) {
node_t *prev = NULL;
node_t *current = head;
node_t *next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
void print_list(node_t *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
node_t *head = NULL;
head = append(head, 1);
head = append(head, 2);
head = append(head, 3);
head = append(head, 4);
head = append(head, 5);
printf("Original list: ");
print_list(head);
head = reverse(head);
printf("Reversed list: ");
print_list(head);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int data;
struct node_s *next;
} node_t;
node_t *create_node(int data) {
node_t *new_node = malloc(sizeof(node_t));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
node_t *append(node_t *head, int data) {
node_t* new_node = create_node(data);
if (NULL == head) {
head = new_node;
} else {
node_t *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
return head;
}
node_t *range_reverse(node_t *head, int k) {
node_t *prev = NULL;
node_t *current = head;
node_t *next = NULL;
int count = 0;
while (current != NULL && count < k) {
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}
if (next != NULL) {
head->next = range_reverse(next, k);
}
return prev;
}
void print_list(node_t *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
node_t *head = NULL;
head = append(head, 1);
head = append(head, 2);
head = append(head, 3);
head = append(head, 4);
head = append(head, 5);
head = append(head, 6);
head = append(head, 7);
head = append(head, 8);
head = append(head, 9);
head = append(head, 10);
printf("Original list: ");
print_list(head);
head = range_reverse(head, 3);
printf("Reversed list: ");
print_list(head);
return 0;
}