java实现链表反转
java实现链表反转
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
/**
* 链表反转,head为当前节点
*/
public ListNode ReverseList(ListNode head) {
ListNode prev = null;
ListNode next = null;
while(head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
//返回反转后链表的头结点
return prev;
}