c_cpp C中的单链表 - 现在只实现交换

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp C中的单链表 - 现在只实现交换相关的知识,希望对你有一定的参考价值。

#include<stdio.h>
#include<assert.h>

typedef struct _List {
  int data;
  struct _List* _next;
} List;

void build_link_list(List* l, size_t n) {
    List* p = l;
    int i = 0;
    while (n--) {
        ++l;
        p->data = i++;
        p->_next = l;
        if (n > 0) p = l;
    }
    // p is now at the end of the list
    p->_next = NULL;
}

void print_link_list(List* listPtr) {
    while (listPtr != NULL) {
        printf("%d -> ", listPtr->data);
        listPtr = listPtr->_next;
    }
    printf("NULL\n");
}

int swap_list(List **head, List *a, List *b) {
    if (a == NULL || b == NULL) return 1;
    if (a == b) return 0;

    List* prev_a = NULL;
    List* prev_b = NULL;
    List* tmp = *head;

    // find a, b in list; return 2 if not both exist
    int found = 0;
    if (a == *head) found++;
    if (b == *head) found++;

    while (tmp->_next != NULL && found != 2) {
        if (tmp->_next == a) { prev_a = tmp; found++; }
        if (tmp->_next == b) { prev_b = tmp; found++; }
        tmp = tmp->_next;
    }
    if (tmp->_next == NULL && found != 2) return 2;

    // update next
    if (prev_a != NULL) prev_a->_next = b;
    if (prev_b != NULL) prev_b->_next = a;

    // swap next
    tmp = a->_next;
    a->_next = b->_next;
    b->_next = tmp;

    // update head
    if (a == *head) {
        *head = b;
    } else if (b == *head) {
        *head = a;
    }

    // successfully finished
    return 0;
}

int main() {
    const size_t SIZE = 7;
    List listTest[SIZE];
    List* listTestHeadPtr = listTest;

    build_link_list(listTest, SIZE);
    print_link_list(listTestHeadPtr);

    int rtn;

    for (size_t i = 0; i < SIZE; i++) {
        for (size_t j = i; j < SIZE; j++) {
            printf("Swapping %d with %d...\n", (int) i, (int) j);

            rtn = swap_list(&listTestHeadPtr, listTest + i, listTest + j);
            assert(!rtn);
            print_link_list(listTestHeadPtr);
        }
    }
}

以上是关于c_cpp C中的单链表 - 现在只实现交换的主要内容,如果未能解决你的问题,请参考以下文章

在C中的单链表中交换位置

c_cpp 交替拆分给定的单链表

c_cpp 单链表的快速排序

c_cpp FP风格的反向单链表

c_cpp 用于检查单链表是否为回文的功能

DS单链表--结点交换