输入一个链表,反转链表后,输出新链表的表头
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}
代码思路
在每一次循环中,都反转了一个箭头(即链表中的节点方向),反转后再重新对pre,head、next进行赋值,以便下一次的箭头反转。
本文介绍了如何使用Java代码反转一个链表,并在反转后输出新链表的表头。通过循环操作,每次反转链表的一个节点,直至完成整个链表的反转。

被折叠的 条评论
为什么被折叠?



