c语言 反向链表

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode*t,*p=NULL,*next=NULL;
    t=head;
    while(t!=NULL)
    {
        next=t->next;//首先保存下一结点,防止断连
        if(p==NULL)//若当前为第一结点
        {
          p=t;//p指向当前结点
          p->next=NULL;//将最开始进行封装,防止无限指向
          t=next;//t指向下一节点
          continue;
        }
        t->next=p;//当前结点指向上一结点
        p=t;//p原本为上一结点,现右移
        t=next;//t指向下一节点
    }
    return p;//返回反转后的链表
}

要将链表反向连接,可以使用三个指针来完成操作。首先,将当前节点的下一个节点保存在一个临时指针中,然后将当前节点的下一个节点指向前一个节点,最后将前一个节点指向当前节点。重复这个过程直到遍历完整个链表。最后,将最后一个节点设置为新的头节点。 以下是一个示例代码来演示如何在C语言中将链表反向连接: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构 struct Node { int data; struct Node* next; }; // 反向连接链表函数 struct Node* reverseLinkedList(struct Node* head) { struct Node* prev = NULL; struct Node* current = head; struct Node* next = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } head = prev; return head; } // 打印链表函数 void printLinkedList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } // 主函数 int main() { // 创建链表 struct Node* head = (struct Node*)malloc(sizeof(struct Node)); struct Node* second = (struct Node*)malloc(sizeof(struct Node)); struct Node* third = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; head->next = second; second->data = 2; second->next = third; third->data = 3; third->next = NULL; printf("原始链表:"); printLinkedList(head); // 反向连接链表 head = reverseLinkedList(head); printf("反向连接后的链表:"); printLinkedList(head); return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值