反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
核心思想:修改链表的next指向,需要记录三个结点的指针来修改
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//改变next指向
//将下一个结点的next指针指向当前结点
ListNode cur = head;
ListNode pre = null;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}