1.题目描述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
2.算法分析
定义pre当前cur节点的前一个节点,cur指向head指向的节点.
当前while循环中,
pre = cur, pre指向cur指向的节点
cur = head,cur指向head指向的节点
head = head.next,head指向的是head的下一个节点
cur.next = pre,// 转变指针方向。
3.代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode pre = null;
ListNode cur = null;
while(head != null){
pre = cur;
cur = head;
head = head.next;
cur.next = pre;
}
return cur;
}
}