面试中问了一个链表对折的问题,写的完全不着边。后来百度了一下,自己根据原理重新写了一下。
package leecode;
public class FoldLinkedList {
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
Node node7 = new Node(7);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
Node head = node1;
traverseList(head);
//使用快慢指针,找到中间对折处节点
Node fast, slow;
fast=slow=node1;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}
//slow是中间节点,list2是第二个链表。
Node list2 = slow.next;
slow.next = null;
//将第二个链表反转
Node head2 = reverseList(list2);
//将list2插入到list1中
Node head1, temp,temp2;
head1 = node1;
// traverseList(head1);
// traverseList(head2);
while(head1 != null && head2 != null){
temp = head1.next;
temp2 = head2.next;
head1.next = head2;
head2.next = temp;
head1 = temp;
head2 = temp2;
}
head = node1;
traverseList(head);
}
//遍历链表
public static void traverseList(Node head){
System.out.println("***********list output**************");
while(head != null){
System.out.println(head.value);
head = head.next;
}
}
public static Node reverseList(Node head){
Node pre, cur, temp;
pre=null;
cur=head;
while(cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
//
}
class Node{
int value;
Node next;
Node(int value){
this.value = value;
}
}