/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
//新建链表
class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
ListNode headA=new ListNode(head.val);
headA.next = null;
head = head.next;
while(head!=null){
ListNode p = new ListNode(head.val);
p.next = headA;
headA = p;
head = head.next;
}
return headA;
}
}
//该方***改变head的结构,作为传递参数为什么会改变呢????
class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
ListNode curr = head,pre = null,next;
while(curr!=null){
next = curr.next; //next指向未反转链表的第一个节点的下一节点,用于保存数据;
curr.next = pre; //将当前节点的下一节点指向已反转链表的头节点
pre = curr; //将pre指针向当前节点
curr = next; //将curr指针指向next节点,也就是pre,curr指针向后移动
}
return pre; //最后返回pre指针,该指针指向头节点
}
}