当前位置: 代码迷 >> 综合 >> 剑指 Offer JZ15 反转链表
  详细解决方案

剑指 Offer JZ15 反转链表

热度:98   发布时间:2024-02-07 20:28:38.0

题目描述

输入一个链表,反转链表后,输出新链表的表头。

迭代 使用头插法

/*
public class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}
}*/
public class Solution {public ListNode ReverseList(ListNode head) {ListNode first=new ListNode(-1);while(head!=null){ListNode next=head.next;head.next=first.next;first.next=head;head=next;}return first.next;}
}

使用递归

/*
public class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}
}*/
public class Solution {public ListNode ReverseList(ListNode head) {//使用递归if(head==null||head.next==null){return head;}ListNode next=head.next;head.next=null;ListNode newHead=ReverseList(next);next.next=head;return newHead;}
}

 

  相关解决方案