牛客算法篇面试必刷——BM1反转链表
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode r = head;
ListNode p = head.next;
r.next = null;
ListNode s;
while(p!=null){
s = p.next;
p.next = r;
r = p;
p = s;
}
return r;
}
}