反转单链表和双链表 代码如下:
public Node revareseList(Node head){
Node pre = null;
Node next = null;
while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public Node reverseTwoList(Node head){
Node pre = null;
Node next = null;
while(head != null){
next = head.next;
head.next = pre;
head.last = next;
pre = next;
head = next;
}
return pre;
}
反转链表再from到to之间的链表
1.保留from前的一个链表,和to以后的一个链表,反转from到to之间的链表然后用上述两个链表链接
public Node reversePartNode(Node head, int from, int to){
Node node = head;
Node fpre = null;
Node tpre = null;
int len = 0;
while(node != null){
len++;
fpre = len == from - 1 ? node : fpre;
tpre = len == to + 1 ? node : tpre;
node = node.next;
}
if(from > to || from < 1 || to > len){
return head;
}
node = fpre == null ? head : head.next;
node.next = tpre;
Node node2 = node.next;
Node next = null;
while(node != tpre){
next = node2.next;
node2.next = node;
node = node2;
node2 = next;
}
if(fpre != null){
fpre.next = node;
return head;
}
return node;
}
2.直接再本地反转并链接,为保证头节点为head的情况,自己创建一个头节点。
public Node reversePartNode2(Node head, int from, int to){
if(head == null || head.next == null){
return head;
}
Node res = new Node(1); res.next = head;
Node first = res;
int i = 0;
while(i < from){
i++;
first = first.next;
}
head = first.next;
while(i < to){
Node next = head.next;
head.next = next.next;
next.next = head;
first.next = next;
i++;
}
return res.next;
}