【题目】
分别实现反转单向链表和反转双向链表的函数
【要求】
如果链表长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1)
【分析思路及代码实现】
反转单向链表:
1.找到某一个节点的下一个结点
2.找到某一个结点的下一个位置
3.把后边的节点都移动到他的前边一位去
public static Node reverseList(Node head) {
Node pre=null;
Node next=null;
while(head!=null) {
//1.找到下一个结点(数据加上指针)
next=head.next;
//2.下一个结点的位置
head.next=pre;
//3.下一个结点位置上存放的是原来的前一个结点
pre=head;
//4.前一个结点位置上存放的是原来的后一个结点
head=next;
}
return pre;
}
反转双向链表:
1.找到某个结点的下一个结点数据
2.找到某个结点的上一个位置和后一个位置
3.把后边的节点都移到他的前一位上去
//1.双向链表的结构
public static class DoubleNode {
public int value;
public DoubleNode next;
public DoubleNode last;
public DoubleNode(int data) {
this.value=data;
}
}
//2.反转双向链表的方法
public static DoubleNode reverseList(DoubleNode head) {
DoubleNode pre=null;
DoubleNode next=null;
while(head!=null) {
//1.找到下一个结点用next表示(结点找到了)
next=head.next;
//2.找到后边位置(要移动到前边位置上去)
head.next=pre;
//3.找到前边的位置(要移动到后边位置上去)
head.last=next;
//4.head作为的是中间数,前边位置上放的原来后边的数就是head,head相当于中间位置,它放的是后边的节点
pre=head;
head=next;
}
return pre;
}