第一种方法: 借助栈的先进后入原则
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode ReverseList (ListNode head) {
// write code here
if(head ==null || head.next ==null){
return head ;
}
Stack<ListNode> ss = new Stack();
while(head!=null){
ss.add(head);
head = head.next ;
}
ListNode res = ss.pop();
ListNode cur = res ;
while(!ss.isEmpty()){
ListNode node = ss.pop();
cur.next = node;
cur = cur.next ;
}
cur.next = null ;
return res ;
}
}
第二种:使用头插法:
虚拟一个头结点,尾结点 ;
head >> 2 >> 3 >>4>> tail
例如上面的链接,如果需要再head插入1,则首先需要获取原先的head.next 缓存temp,然后让head 指向 1 即 head.next = new Node() ; 然后让新增节点的next指向temp 即 new Node().next = temp ; 就可以完成头插法。所以所谓的头插法反转就是新增了一个新的链表,然后遍历原先的链表,每次使用头插法插入到新的链表即可;
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode ReverseList (ListNode head) {
// write code here
if(head == null || head.next ==null){
return head ;
}
ListNode newHead = new ListNode(-1);
ListNode cur = head ;
while(cur!=null){
ListNode next = cur.next ;
addToHead(newHead,cur);
cur =next;
}
return newHead.next;
}
public void addToHead(ListNode newHead ,ListNode node){
// head >> 2 >>3 >> tail 新增1
ListNode temp = newHead.next ;
newHead.next = node ;
node.next = temp ;
}
}
本文介绍了两种在Java中反转链表的方法:一是利用栈的先进后出特性,二是通过头插法。首先演示了使用栈逐个取出节点并插入到新链表的示例,接着展示了如何通过虚拟头结点实现头插法反转链表。
613

被折叠的 条评论
为什么被折叠?



