反转链表 核心是反转next指针 以下是非递归实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null) return null;
if(head!=null&&head.next==null){
return head;
}
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;//存储当前指针next域 以便于指针的后移
head.next=pre; //反转当前节点
pre=head; //这两步是指针后移
head=next;
}
return pre;
}
}