牛客网反转链表JAVA 链表头插法的使用

1.## 牛客网反转链表JAVA 链表头插法的使用##

项目场景:

牛客网 反转链表题

问题描述:

输入一个链表,反转链表后,输出新链表的表头。
示例1
输入
{1,2,3}
返回值
{3,2,1}

原因分析:

一个好的反转链表的方法

解决方案:

import java.util.*;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null){
            return null;
        }
        if(head.next==null){
            return head;
        }
        ListNode temp = head;
        ListNode Next =null;
        ListNode head1= new ListNode(0);
        while(temp!=null){
            Next = temp.next;
            temp.next=head1.next;
            head1.next=temp;
            temp=Next;
        }
        return head1.next;
    }
}

问题描述:

从头开始遍历,逐个加入到新的头节点中,使用头插法解决

解决方案:

**要设置两个ListNode ,一个temp从头节点开始,再定义一个Next为头节点的下一个节点(Next=temp.next),再将temp.next指向新节点的next,再将temp=Next,当temp==null的时候结束循环。

while (temp!=null){
            next=temp.next;
            temp.next=reverseHead.next;
            reverseHead.next=temp;
            temp=next;
        }
头插法是一种反转链表的方法,它通过将原链表的每个节点插入到新链表的头部,从而实现链表的反转。下面是使用头插法反转链表的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; } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值