【算法与数据结构】链表逆序、相邻两元素逆序、探测环路

链表常见操作有:

  • 链表逆序
  • 链表每相邻两个元素逆序,例如 1, 2, 3, 4 => 2, 1, 4, 3
  • 探测是否构成环路
#include <stdio.h>
#include <stdlib.h>

typedef struct NodeStruct {
    int data;
    struct NodeStruct *next;
} Node, *Position, *List;

void initList(List *l) {
    *l = malloc(sizeof(Node));
    (*l)->next = NULL;
}

void insertList(List l, int v) {
    Position tmp = malloc(sizeof(Node));
    Position cur = l;
    tmp->data = v;
    tmp->next = NULL;
    while(cur->next != NULL) {
        cur = cur->next;
    }
    cur->next = tmp;
}

void printList(List l) {
    Position cur = l->next;
    printf("\nlist begin\n");
    while(cur != NULL) {
        printf("%4d", cur->data);
        cur = cur->next;
    }
    printf("\nlist end\n");
}

// 1, 2, 3, 4 => 4, 3, 2, 1
void reverseList(List list) {
    Position tmp;
    List new;
    new = malloc(sizeof(Node));
    new->next = NULL;
    while (list->next != NULL) {
        tmp = list->next;
        list->next = list->next->next;
        tmp->next = new->next;
        new->next = tmp;
    }
    list->next = new->next;
    free(new);
}

// 1, 2, 3, 4 => 2, 1, 4, 3
void twoReverseList(List list) {
    Position tmp = list, swp;
    while (tmp->next != NULL && tmp->next->next != NULL) {
        swp = tmp->next;
        tmp->next = tmp->next->next;
        swp->next = tmp->next->next;
        tmp->next->next = swp;
        tmp = tmp->next->next;
    }
}

// 探测链表是否构成环路
int detectCycle(List list) {
    Position fast, slow;
    fast = list->next;
    slow = list;
    while (fast != NULL) {
        if (fast == slow) {
            return 0;
        }
        fast = fast->next->next;
        slow = slow->next;
    }
    return -1;
}

int main(void) {
    int ret;
    List l;
    initList(&l);
    insertList(l, 5);
    insertList(l, 8);
    insertList(l, 2);
    insertList(l, 78);
    
    printList(l);
    reverseList(l);
    printList(l);
    twoReverseList(l);
    printList(l);
    
    ret = detectCycle(l);
    printf("%d\n", ret);
    l->next->next->next->next->next = l->next->next;
    ret = detectCycle(l);
    printf("%d\n", ret);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值