头插法反转链表——Java实现

题目:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
在这里插入图片描述OJ链接:https://leetcode.cn/problems/reverse-linked-list/description/

解答:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head ==  null){
            return null;
        }
        if(head != null){
            ListNode cur = new ListNode();
            cur = head.next;
            ListNode curnext = new ListNode();
            head.next = null;
            while(cur != null){
                curnext = cur.next;
                cur.next =  head;
                head = cur;
                cur = curnext;
            }
        }
        return head;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值