链表反转(Java)
1.虚拟节点头插
长命指针:curr
短命指针:next
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) {
ListNode dummy = new ListNode(-1);
ListNode curr = head;
while(curr!=null){
ListNode next = curr.next;
curr.next = dummy.next;
dummy.next = curr;
curr = next;
}
return dummy.next;
}
}
2.迭代操作原链表(递归原理相似)
动画
代码
长命指针:pre curr
短命指针:next
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) {
ListNode pre = null;
ListNode curr = head;
while(curr!=null){
ListNode next = curr.next;
curr.next = pre;
pre = curr;//注意顺序
curr = next;
}
return pre;
}
}