C语言如何截取部分链表?

C语言如何截取链表呢,假设我现在有一段链表 1,2,3,4,5,6
我怎么才能截取到它的中间部分2,3,4,5呢?

阅读 1.7k
1 个回答
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
} Node;

Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if(newNode == NULL) {
        printf("Error creating a new node.\n");
        exit(0);
    }
    newNode->data = data;
    newNode->next = NULL;

    return newNode;
}

Node* sliceLinkedList(Node* head, int start, int end) {
    Node* current = head;
    Node* startNode = NULL;
    Node* endNode = NULL;

    // 找到开始和结束节点
    while(current != NULL) {
        if(current->data == start) {
            startNode = current;
        }
        if(current->data == end) {
            endNode = current;
            break;
        }
        current = current->next;
    }

    if(startNode != NULL && endNode != NULL) {
        endNode->next = NULL;
        return startNode;
    }

    return NULL;
}

int main() {
    Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);
    head->next->next->next->next->next = createNode(6);

    Node* sliced = sliceLinkedList(head, 2, 5);

    Node* current = sliced;
    while(current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    return 0;
}
推荐问题
logo
Microsoft
子站问答
访问
宣传栏