反转链表
构建链表结构:
public class ListNode {
int val;
ListNode next=null;
ListNode(int val){
this.val=val;
}
}
反转链表:
算法思路:
1.若链表为空,直接返回头结点
2.若链表不为空,设置pre,cur,next三个指针,设置初始值为head,其余两个指针为空。
3.首先令next指向cur的下一个元素,然后令cur.next指向pre,完成了cur指针的反转,最后更新pre和cur;
4.重复上述过程,直至cur==null,此时pre的值就是原链表的最后一个元素,即新链表的第一个元素,返回pre。
代码:
public class ReverseList {
public ListNode ReverseList(ListNode head){
if(head==null){
return head;
}
ListNode pre=null;
ListNode cur=head;
ListNode next=null;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}