Reverse a singly linked list.
用三个节点保存前、中、后三个节点即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}else if(head.next==null){
return head;
}
ListNode prev,last;
prev=head;
head=head.next;
prev.next=null;
if(head.next==null){
head.next=prev;
}else{
last=head.next;
while(last!=null){
head.next=prev;
prev=head;
head=last;
last=last.next;
}
head.next=prev;
}
return head;
}
}
本文介绍了一种使用三个节点(前、中、后)来实现单链表反转的方法。通过迭代更新指针的方式,该算法能够高效地完成链表元素顺序的反转。
146

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



