解决思路:共有三种情况,1.链表为空;2.链表中只有一个元素;3.链表中有多个元素。前两种情况直接返回入参;第三种情况,创建一个新的头节点和尾节点,每次循环将原链表中的指向反转,当最后两个节点反转时,注意新建头节点的指向
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return head;
}
if(head.next==null){
return head;
}
ListNode newtail=new ListNode(head.val);
while(head.next.next!=null){
ListNode newhead=new ListNode(head.next.val);
newhead.next=newtail;
head=head.next;
newtail=newhead;
}
ListNode newHead=new ListNode(head.next.val);
newHead.next=newtail;
return newHead;
}
}
京公网安备 11010502036488号