CT01-反转链表(Java)
1.代码思路
1->2->3->NULL
NULL<-3<-2<-1
先设置一个pre指针和cur指针
pre指针指向NULL
cur指针指向头结点
定义一个next指针,存储临时变量(用于cur的后移操作)
反转箭头方向
然后pre和cur指针后移
2.java代码实现
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode reverseList(ListNode head) {ListNode pre=null;//头结点的指针指向空ListNode cur=head;//头结点while(cur!=null){ListNode tmp=cur.next;//临时变量用于cur的后移操作,因为下一步要改变cur.next箭头方向,会对cur.next有影响cur.next=pre;//反转箭头的方向pre=cur;cur=tmp;}return pre;}
}