链表翻转分两部分,链表整表翻转和链表部分翻转。下面讨论非递归的做法,递归的做法以后有空再说。。。
先说链表整表翻转,核心四句话:
next = p.next;
p.next = pre;
pre = p;
p = next;
顾名思义,pre是p前面的节点,next是p后面的节点。举个例子,下图是一个链表节点翻转前的状态:
上面的代码执行之后,变成下图:
只要重复这个过程并最后处理头结点(1指向2的指针)就能完成链表的翻转。
有了上面的分析,再来分析链表部分翻转,假设要翻转下面这个链表3,4,5
那么,很明显,应当先遍历链表到3再开始翻转。显然,翻转完后链表的状态是下图:
要完成翻转,只需把p1指向5(pre),p2指向6(p)即可。逻辑就是这样,代码如下:
public class Main {
public static void main(String[] args) {
Node p0 = createList(10);
printList(p0);
Node p1 = reverse(p0,3,6);
printList(p1);
}
public static Node reverse(Node head){
if(head==null||head.next==null)
return head;
else{
Node pre = head;
Node p = pre.next;
Node next = null;
while(p!=null){
next = p.next;
p.next = pre;
pre = p;
p = next;
}
head.next = null;
return pre;
}
}
public static Node reverse(Node head,int from,int to){
if(head==null||head.next==null)
return head;
else{
Node pHead = new Node(0);
pHead.next = head;
int i = 0;
Node pPre = pHead;
while(i<from){
pPre = head;
head = head.next;
i++;
}
Node pre = head;
Node p = pre.next;
Node next = null;
while(i<to){
next = p.next;
p.next = pre;
pre = p;
p = next;
i++;
}
head.next = p;
pPre.next = pre;
return pHead.next;
}
}
public static Node createList(int num) {
Random random = new Random();
Node pHead = new Node(random.nextInt(100));
for (int i = 0; i < num - 1; i++) {
Node p = new Node(random.nextInt(100));
p.next = pHead.next;
pHead.next = p;
}
return pHead;
}
public static void printList(Node p) {
while (p != null) {
if (p.next != null)
System.out.print(p.value + "->");
else
System.out.println(p.value);
p = p.next;
}
}
}
在部分翻转链表的代码中我设置了一个前置节点,这样处理头结点比较容易,其它的应该没什么好解释的了。收工。