输入一个链表,反转链表后,输出新链表的表头。
package 剑指Offer.反转链表;
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode current = head;
ListNode next = null;
ListNode previous = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
网友评论