.连接两个升序链表
1.建立一个节点负责串起新的表;
2.当两个头节点都不为空时,判断头两节点数据的大小;
小的被新建节点串起,然后节点后移;
3.当有一条链被串完时,直接串另一个节点;
public static Node mergeTwoLists(Node headA, Node headB) {
Node newHead = new Node();
Node tmp = newHead;
while (headA != null && headB != null){
if(headA.data < headB.data) {
newHead.next = headA;
headA = headA.next;
tmp = tmp.next;
}else {
newHead.next = headB;
headB = headB.next;
tmp = tmp.next;
}
}
if(headA!= null) {
tmp.next = headA;
}
if(headB != null) {
tmp.next = headB;
}
return newHead.next;
}
返回两个链表的第一个交点
1.得的出两链表的长度差值len
2.建立两个节点,让其中一个节点先走len步
3.两个节点同时走直到他们相等
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;
}
//pL指向最长的单链表
//pS指向最短的单链表
//len 肯定是一个正数
for (int i = 0; i < len; i++) {
pL = pL.next;
}
//pL和pS此时已经在同一期起跑线上了
//可以一人一步走
while (pL != null && pS != null && pL != pS) {
pL = pL.next;
pS = pS.next;
}
if(pL == null || pS == null ) {
return null;
}
return pL;
}
链表是否有为回文结果(形似123454321)
1.创建快慢两个指针,分别到达链表的尾部和中间
2.快指针返回头部,慢指针在中间开始对后半段进行反转
3.后移头节点和慢指针并比较其内的数值,有不相等则不是回文结果
public static boolean chkPalindrome(Node head){//是否回文
if(head == null ){//空表
return false;
}
if(head.next == null) {//单节点
return true;
}
Node fast = head;
Node slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//2、翻转
Node p = slow.next;
while (p != null) {
Node pNext = p.next;
p.next = slow;
slow = p;
p = pNext;
if(p != null) {
pNext = p.next;
}
}
//3、进行判断
while (head != slow) {
if(head.data != slow.data) {
return false;
}
if(head.next == slow) {
return true;
}
head = head.next;
slow = slow.next;
}
return true;
}