反转单向链表

链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。而单向链表就是在每一个结点中除了保存的数据之外只有一个指向下一个节点的指针。双向链表的每一个节点除了保存的数据之外,即有指向下一个节点的指针还有指向上一个节点的指针。

单链表节点的关系似乎像无间道中的人物关系,只有你的上级(上一个节点)知道你,你的上级能找到你而你却找不到他。所以整个过程中要想让别知道自己存在就必须确保你的上级(上一个结点)没有挂了,如果你的上级找不到了并且他没有把你的关系告诉别人(用另一个指针保存),那么你也就挂掉了。

单向链表

创建单向链表

Created with Raphaël 2.1.2 开始 Data *head = NULL Data*tempHead = NULL while i < n? 1) 创建Data结构体temp,设置temp->data = i, temp -> next = NULL head == NULL head = temp,tempHead = head 结束 tempHead ->nextPoint = temp; tempHead = temp; yes no yes no

反转链表

Created with Raphaël 2.1.2 开始 linkHead Data *tempHead = linkHead Data*prePoint = NULL Data *next = NULL while (tempHead) if (tempHead == linkHead) next = tempHead->nextPoint,temHead->nextPoint = NULL, prePoint = tempHead temp = next next = tempHead->nextPoint,temHead->nextPoint = prePoint, pre = tempHead; 结束 yes no yes no
#include <stdio.h>
#include <stdlib.h>
typedef struct data {

    int data;
    struct data *nextPoint;
}CustomData;


CustomData* createLink(int a[10], int n) {

    CustomData *head = NULL;
    CustomData *p = NULL;
    for (int i = 0; i < n; i++) {
        CustomData *temp= (CustomData *)malloc(sizeof(CustomData));
        temp -> data = a[i];
        temp->nextPoint = NULL;
        if (head == NULL) {
            head = temp;
            p = head;
        } else {
            p ->nextPoint = temp;
            p = temp;
        }
    }
    return head;
}
 CustomData * reverseLink(CustomData *link) {

    CustomData *tempHead = link;
    CustomData *next = NULL;
    CustomData *pre = NULL;
    while (tempHead) {
        if (tempHead == link) {
            next = tempHead->nextPoint;
            tempHead ->nextPoint = NULL;
            pre = tempHead;
        } else {
            next = tempHead->nextPoint;
            tempHead -> nextPoint = pre;
            pre = tempHead;
        }
        tempHead = next;
        if (tempHead != NULL) {
            printf("%d\n",tempHead ->data);
        }

    }
    return pre;
}


int main(int argc, const char * argv[]) {
    // insert code here...

    int a [10] = {1,2,3,4,5,6,7,8,9,10};
    CustomData *head = createLink(a, 10);
   head =  reverseLink(head);

    while (head) {
        printf("%d", head->data);
        head = head->nextPoint;
    }


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值