以代码为主,帮助自己较好的理解思想。
1.反转链表
//反转链表
public ListNode ReverseList(ListNode head){
ListNode current = head;//当前节点
ListNode pre = null;
ListNode reverseHead = null;//反转后的头结点
ListNode temp = null;
while(current != null){
temp = current.next;
current.next = pre;
if(null == temp){
reverseHead = current;
break;
}
pre = current;
current = temp;
}
return reverseHead;
}
2.带环链表-环的入口节点(一步两步)
//单向带环链表 环的入口节点 ---相遇肯定是在环上
public ListNode EntryNodeOfLoop(ListNode pHead){
if(pHead.next == null || pHead.next.next == null){//一步两步
return null;
}
ListNode slow = pHead.next;
ListNode fast = pHead.next.next;
while(fast != null){
if(slow == fast){//第一次相遇后(在环上)
fast = pHead;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return fast;
}
//如果还没有第一次相遇 一步两步
slow = slow.next;
fast = fast.next.next;
}
return null;
}
3.从尾至头输出链表节点值(递归)
ArrayList<Integer> arrList = new ArrayList<Integer>();
//从尾至头输出链表节点值
public ArrayList<Integer> PrintListFromTailToHead(ListNode head){
if(head != null){
PrintListFromTailToHead(head.next);
arrList.add(head.val);
}
return arrList;
}
4.两个链表的第一个公共节点
//两个链表的第一个公共节点
public ListNode FindFirstCommonNode(ListNode pHead1,ListNode pHead2){
if(pHead1 == null || pHead2 == null){
return null;
}
int count1 = GetLength(pHead1);
int count2 = GetLength(pHead2);
ListNode p = pHead1;
ListNode q = pHead2;
if(count1 > count2){
for(int i = 0;i < count1-count2;i++){//长度大的先走几步
p = p.next;
}
while(p != q){
p = p.next;
q = q.next;
}
}else if(count1 < count2){
for(int j = 0;j < count2-count1;j++){
q = q.next;
}
while(p != q){
p = p.next;
q = q.next;
}
}else{
while(p != q){
p = p.next;
q = q.next;
}
}
return p;
}
public int GetLength(ListNode pHead){//获取链表长度
int count = 0;
while(pHead != null){
count++;
pHead = pHead.next;
}
return count;
}
5.链表的倒数第K个节点
//链表的倒数第K个节点
public ListNode FindKthToTail(ListNode head,int k){//k的值从1开始
if(head == null || k <= 0){
return null;
}
ListNode p = head;
ListNode q = head;
for(int i = 1;i < k;i++){//p先走
if(p.next != null){
p = p.next;
}else{
return null;
}
}
while(p.next != null){
p = p.next;
q = q.next;
}
return q;
}
链表相关,先整理这些,后续补充。