class LinkedListNode {
int val;
LinkedListNode next;
LinkedListNode(int val) {
this.val = val;
}
}
public class Solution {
public LinkedListNode reverseLinkedList(LinkedListNode head) {
if(head==null || head.next==null) {
return head;
}
ListNode before = null;
ListNode current = head;
ListNode after;
while(current != null) {
after = current.next;
current.next = before;
before = current;
if(after != null) {//如果当前节点之后还有节点
current = after;
} else {//如果已经到了链表末尾
break;
}
}
return current;//返回新链表的头节点
}
}
算法题——剑指Offer24:反转链表
最新推荐文章于 2022-02-14 16:22:19 发布