一.方法一
思路:建立虚拟头节点进行反转
代码:
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return head;
}
ListNode cc=head.next;
ListNode p=new ListNode(-1);
while(head!=null){
cc=head.next;
head.next=p.next;
p.next=head;
head=cc;
}
return p.next;
}
}
二.方法二
思路:直接操作链进行反转
代码:
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return head;
}
ListNode cc=head.next;
ListNode p=null;
while(head!=null){
cc=head.next;
head.next=p;
p=head;
head=cc;
}
return p;
}