反转链表(C)

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

//递归法
// struct ListNode* reverseList(struct ListNode* head){
//     if((head == NULL) || (head->next == NULL))
//         return head;
//     struct ListNode *NewHead = reverseList(head->next);
//     head->next->next = head;
//     head->next = NULL;
    
//     return NewHead;
// }
//非递归法
struct ListNode* reverseList(struct ListNode* head){
    struct ListNode *prev , *curr , *temp;
    prev = NULL;
    curr = head;
    temp = head;
    while(temp)
    {
        temp = temp->next;
        curr->next = prev;
        prev = curr;
        curr = temp;
    }
    return prev;
}

 非递归采用三个指针

递归暂时不是特别懂,他应该是有一种规律,用递归的一种套路一样。(弄懂了再来补充)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
头插法是一种反转链表的方法,它通过将原链表的每个节点插入到新链表的头部,从而实现链表的反转。下面是使用头插法反转链表C语言代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 struct ListNode { int val; struct ListNode* next; }; // 头插法反转链表 struct ListNode* reverseList(struct ListNode* head) { struct ListNode* newHead = NULL; // 新链表的头节点 while (head != NULL) { struct ListNode* nextNode = head->next; // 保存下一个节点的指针 head->next = newHead; // 将当前节点插入到新链表的头部 newHead = head; // 更新新链表的头节点 head = nextNode; // 移动到下一个节点 } return newHead; } // 创建链表 struct ListNode* createList(int* nums, int size) { struct ListNode* head = NULL; struct ListNode* tail = NULL; for (int i = 0; i < size; i++) { struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->val = nums[i]; newNode->next = NULL; if (head == NULL) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } } return head; } // 打印链表 void printList(struct ListNode* head) { while (head != NULL) { printf("%d ", head->val); head = head->next; } printf("\n"); } int main() { int nums[] = {1, 2, 3, 4, 5}; int size = sizeof(nums) / sizeof(nums[0]); struct ListNode* head = createList(nums, size); printf("原链表:"); printList(head); struct ListNode* newHead = reverseList(head); printf("反转后的链表:"); printList(newHead); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值