输入一个链表,反转链表后,输出新链表的表头。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next==null){
return head;
}
ListNode left=head;
ListNode mid=left.next;
ListNode right = mid.next;
while(right!=null){
mid.next = left;
left = mid;
mid = right;
right = right.next;
}
mid.next = left;
head.next = null;
head = mid;
return head;
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode newListNode=null;
while(head!=null){
//把源链表进行头插法到新的node中
ListNode old_head = head;
head = head.next;
old_head.next = newListNode;
newListNode = old_head;
}
return newListNode;
}
}
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1969uaf40c6k3