c語言雙向鏈表反轉(zhuǎn)的方法是什么

小億
103
2023-12-20 13:07:57
欄目: 編程語言

要實(shí)現(xiàn)C語言雙向鏈表的反轉(zhuǎn),可以采取以下步驟:

  1. 定義一個(gè)指向鏈表頭部的指針和一個(gè)指向鏈表尾部的指針,分別稱為head和tail。
  2. 遍歷鏈表,將每個(gè)節(jié)點(diǎn)的prev指針和next指針進(jìn)行交換。
  3. 最后,交換head和tail指針。

以下是一個(gè)示例代碼:

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

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

// 創(chuàng)建鏈表
Node* createLinkedList(int n) {
    Node *head, *p, *newNode;
    int i, data;
    
    head = (Node*)malloc(sizeof(Node));
    head->prev = NULL;
    head->next = NULL;
    
    p = head;
    
    for (i = 0; i < n; i++) {
        newNode = (Node*)malloc(sizeof(Node));
        
        printf("輸入第 %d 個(gè)節(jié)點(diǎn)的值: ", i+1);
        scanf("%d", &data);
        
        newNode->data = data;
        newNode->prev = p;
        newNode->next = NULL;
        
        p->next = newNode;
        p = p->next;
    }
    
    return head;
}

// 反轉(zhuǎn)鏈表
Node* reverseLinkedList(Node* head) {
    Node* temp = NULL;
    Node* current = head;
    
    // 遍歷鏈表并交換prev和next指針
    while (current != NULL) {
        temp = current->prev;
        current->prev = current->next;
        current->next = temp;
        current = current->prev;
    }
    
    // 更新head指針
    if (temp != NULL) {
        head = temp->prev;
    }
    
    return head;
}

// 打印鏈表
void printLinkedList(Node* head) {
    Node* current = head->next;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    int n;
    Node* head;
    
    printf("輸入鏈表長度: ");
    scanf("%d", &n);
    
    head = createLinkedList(n);
    printf("原始鏈表: ");
    printLinkedList(head);
    
    head = reverseLinkedList(head);
    printf("反轉(zhuǎn)后的鏈表: ");
    printLinkedList(head);
    
    return 0;
}

注意:在這個(gè)示例代碼中,我們使用了一個(gè)帶有頭結(jié)點(diǎn)的雙向鏈表,頭結(jié)點(diǎn)的data字段不存儲(chǔ)任何數(shù)據(jù),只是用來方便操作。

0