今天参加面试 上机题,整理一下

有辅助性或指示性的结点(保持往下走),定义为tmp;有实际参与操作的结点

#include <stdio.h>

#include <stdlib.h>
#include <string.h>

#define LEN 11

typedef struct node {
    int data;
    struct node *pnext;
} node_t, *pnode_t;

pnode_t create_link()
{
    int i;
    pnode_t phead;

    phead = (pnode_t)malloc(sizeof(node_t));    
    if (phead == NULL) {
        printf("malloc fail.\n");
        exit(-1);
    }
    memset(phead, 0, sizeof(node_t));

    pnode_t ptail = phead;

    for (i = 0; i < LEN; i++) {
        pnode_t    pnew = (pnode_t)malloc(sizeof(node_t));
        if (pnew == NULL) {
            printf("malloc fail.\n");
            exit(-1);
        }
        memset(pnew, 0, sizeof(node_t));

        pnew->data = i+1;
        pnew->pnext = NULL;
        ptail->pnext = pnew;
        ptail = pnew;
    }

    return phead;
}

void swapNode(pnode_t phead){
    if (phead == NULL){
        printf("phead error!\n");
        return;
    }

    pnode_t head, fir, sec, third;
    head = phead;

    while (head->pnext != NULL){
        fir = head->pnext;

        sec = fir->pnext;
        if (sec == NULL){
            printf("Not OU!\n");
            return;
        }

        third = sec->pnext;
        
    //delete fir
        head->pnext = sec;
    //insert fir
        fir->pnext = third;
        sec->pnext = fir;
        
        head = head->pnext->pnext;
    }
    return;
}

void print_link(pnode_t phead)
{
    pnode_t p = phead->pnext;

    while (p != NULL) {
        printf("%d ", p->data);
        p = p->pnext;
    }
    printf("\n");
}

void reverse_link(pnode_t phead)
{
    pnode_t p, q, ptmp;

    p = phead->pnext;
    q = phead->pnext->pnext;
    ptmp = NULL;

    while (q != NULL) {
        ptmp = q->pnext;
        q->pnext = p;
        p = q;
        q = ptmp;
    }

    phead->pnext->pnext = NULL;
    phead->pnext = p;
}

int main(int argc, char *argv[])
{
    pnode_t phead = NULL;

    phead = create_link();

    print_link(phead);

    swapNode(phead);
    //reverse_link(phead);
    print_link(phead);

    return 0;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值