版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28935065/article/details/77074195
链表分为单向链表和双向链表,无论是哪一种链表,反转都是类似的,区别主要是双向将当前节点的last节点指向next节点。链表反转要注意的就是找到当前节点时,在进行反转前,找到当前节点的上一个节点和下一个节点,这样才能保证每一次的反转后可以移动到下一个节点并继续进行操作。
public class Node {//单链表的节点结构
int data;
Node next=null;
public Node(int data){
this.data=data;
}
}
//单链表反转
public static Node reverseLinkList(Node head) {
// TODO Auto-generated method stub
Node pre=null;
Node next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
public class DoubleNode {//双向链表结构
public int data;
public DoubleNode next;
public DoubleNode last;
public DoubleNode(int data){
this.data=data;
}
}
//反转双向链表
public static DoubleNode reverseDoubleLinkList(DoubleNode head) {
// TODO Auto-generated method stub
DoubleNode pre=null;
DoubleNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
head.last=next;//将last节点指向next节点
pre=head;
head=next;
}
return pre;
}
参考资料
1.《昌旭源代码面试指南——IT名企算法与数据结构题目最优解》 左程云 著