单向链表的逆序实现方式
public static class Node{
private int val;
private Node next;
public Node(int val) {
this.val = val;
}
}
/**
实现单向链表的第一种方式,只通过链表指针的重连来实现
*/
public static Node receiver(Node head){
Node cur = null;
Node next = null;
while(head != null){
next = head.next;
head.next = cur;
cur = head;
head = next;
}
return cur;
}
/**
* 借助list 实现链表翻转。
* @param head
* @return
*/
public static Node receiverList(Node head){
if (null == head){
return null;
}
ArrayList<Node> nodes = new ArrayList<>();
while (head != null){
nodes.add(head);
head = head.next;
}
nodes.get(0).next = null;
int len = nodes.size();
for (int i = 1; i < len;i++){
nodes.get(i).next = nodes.get(i - 1);
}
return nodes.get(len -1);
}
双向链表的实现逆序的两种方式
public static class DoubleNode{
private int val;
private DoubleNode last;
private DoubleNode next;
public DoubleNode(int val) {
this.val = val;
}
}
/**
指针重连的方式实现双向链表的逆序
*/
public static DoubleNode receiverDoubleNode(DoubleNode head){
DoubleNode cur = null;
DoubleNode next = null;
while(head != null){
next = head.next;
head.next = cur;
head.last = next;
head = next;
cur = head;
}
return cur;
}
/**
通过数组实现双向链表逆序
*/
public static DoubleNode testReverseDoubleList(DoubleNode head) {
if (head == null) {
return null;
}
ArrayList<DoubleNode> list = new ArrayList<>();
while (head != null) {
list.add(head);
head = head.next;
}
list.get(0).next = null;
DoubleNode pre = list.get(0);
int N = list.size();
for (int i = 1; i < N; i++) {
DoubleNode cur = list.get(i);
cur.last = null;
cur.next = pre;
pre.last = cur;
pre = cur;
}
return list.get(N - 1);
}
标签:head,cur,单向,DoubleNode,next,链表,null,逆序
From: https://www.cnblogs.com/vip1024/p/17287702.html