在各种笔试面试中,链表都是很常会被问到的数据结构,上次在LeetCode的上刷到反转链表那道题,不难,但是很经典,在很多其他的应用场景中都会用到这个方法,所以今天就整理一篇博客~ 在博客中暂时只写了一种反转链表的应用场景——判断一个链表是否是回文链表。之后遇到其他的会再加上去~
1、首先定义链表结点:
public class ListNode{
int value;
ListNode next;
ListNode(int x){
value=x;
}
}
2、接下来,就是进行链表反转的过程了,使用的是迭代法——头插法来实现的,具体代码如下:
public ListNode reverList(ListNode head){
ListNode next=null,pre=null;
//while循环,直到head==null,说明链表节点全部反转完毕
while(head!=null){
//将head.next赋值给next变量(next指向节点2,先将节点2保存起来)
next=head.next;
//将pre变量赋给head.next(节点1指向null)
head.next=pre;
//将head赋值给pre(即head指向节点1),此时就将节点1设置成了“上一个节点”
pre=head;
//将next赋值给head(即head指向节点2),此时就将节点2设置成了“头结点”
head=next;
}
return pre;
}
3、最后就是在具体的应用场景中,使用到反转链表,例如判断一个链表是否是回文链表——
public boolean isPalindrome(ListNode head){
if(head==null||head.next==null){
return true;
}
ListNode fast=head,slow=head;
//找中间结点
while(fast.next!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//后半段逆置
slow=reverList(slow.next);
//对比前后两段中的数,逐个对比
while(slow!=null){
if(head.value!=slow.value)
return false;
head=head.next;
slow=slow.next;
}
return true;
}