涉及两个单链表的问题
在我们的实际应用中,一个单链表往往难以解决问题,以下我们来关注涉及到两个单链表的问题。
1.找两个单链表的第一个公共节点
找两个单链表的第一个公共节点:
先获取到两个链表长度的差值len;
让长的链表走差值len步,两个再一起走; 保证pL是长的链表,pS 是短的链表;
一起走的时候,相遇即为公共点.
public static Node getIntersectionNode (Node headA,Node headB){
int lenA = 0;
int lenB = 0;
Node pL = headA;
Node pS = headB;
while(pL != null){
lenA ++;
pL = pL.next;
}
while(pS != null){
lenB ++;
pS = pS.next;
}
pL = headA;
pS = headB;
int len = lenA - lenB;
if(len < 0){
pL = headB;
pS =headA;
len = lenB - lenA;
}else {
pL = headA;
pS = headB;
}
for(int i = 0;i < len;i++) {
pL = pL.next;
}
while(pL != null&& pS != null && pL!= pS){
pL = pL.next;
pS = pS.next;
}
if(pL == null || pS ==null){
return null;
}
return pL;// 只有pL 和pS 相遇并且长的链表和短的链表都有后继节点时才会返回
}
2.两个单链表的拼接
//两个单链表的拼接
public Node mergeTwoLists(Node headA,Node headB) {
Node node = new Node(-1);
Node tmp = node;
while(headA != null && headB != null) {
if(headA.data < headB.data) {
tmp.next = headA;
headA = headA.next;
tmp = tmp.next;
} else {
tmp.next = headB;
headB = headB.next;
tmp = tmp.next;
}
}
if(headA != null) {
tmp.next = headA;
}
if(headB != null) {
tmp.next = headB;
}
return node.next;
}
3.创建一个Y型链表
//创建一个Y型链表
public void creatCut(Node headA,Node headB) {
headA.next = headB.next.next;
}
}