[LeetCode][Java] Reverse Linked List

本文介绍两种实现单链表反转的方法:一是通过数组辅助完成反转;二是直接在链表上进行指针操作来实现反转。文章提供了详细的算法分析及代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Reverse a singly linked list.

题意:

倒转单链表.

算法分析:

方法一:

将单链表转化为数组,利用数组倒序重建新的单链表。

代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution 
{
	    public static ListNode reverseList(ListNode head) 
	    {
			ArrayList<Integer> list =new ArrayList<Integer>();

	    	int k=0;
	    	int i;
			if(head==null) return head;
	    	
	    	while(head!=null)
	    	{
	    		list.add(head.val);
	    		head=head.next;
	    		k++;
	    	}
			ListNode res = new ListNode(list.get(k-1));;
			ListNode newhead = res;
			//newhead.next=res;
	    	for(i=k-1;i>=1;i--)
	    	{
	    		res.next=new ListNode(list.get(i-1));
	    		res=res.next;
	    	}
			return newhead;
	        
	    }
}


方法二:

单链表指针反转

代码:

public class Solution 
{
    public ListNode reverseList(ListNode head) 
    {
        ListNode dunmy = head;  //维护初始链表头,用于判断循环结束
        if(head == null || head.next == null)
            return head;
        ListNode pre = null;
        ListNode temp = null;
        while(dunmy.next != null)
        {
            pre = head;              //记录当前节点
            head = dunmy.next;
            temp = head.next;   //保存next
            head.next = pre;
            dunmy.next = temp;
        }
        return head;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值