反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
解决
迭代法
1 → 2 → 3 → 4 → 5 → null
pre cro temp
null ← 1 2 → 3 → 4 → 5 → null
pre cro temp
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) { //pre,cor,temp //pre记录反转后的链表头节点 //cor将要变成头节点 //temp先保存cor的下一个节点,再让cor变成头节点 ListNode cro=head; ListNode pre=null; ListNode temp=null; //先用temp保存cro的下一个节点,改变cro.next的指向,移动pre,再移动cro while(cro!=null){ //xian'bao temp=cro.next; cro.next=pre; pre=cro; cro=temp; } return pre; } }