1.链表篇
1.1删除节点
public void deleteNode(ListNode head,ListNode delNode){
if(head==null||delNode==null)
retrun;
if(head==delNode){
head=null;
}else{
//若delNode刚好是末尾节点,则后移一位
if(delNode.next==null){
ListNode p=head;
while(p.next.next!=null){
p=p.next;
}
p.next=null;
}else{
//将下一个节点的值赋予待删除节点,同时将待删除节点指向下下个节点
delNode.data=delNode.next.data;
delNode.next=delNode.next.next;
}
}
}
1.2翻转链表
public ListNode reverseList(ListNode head){
//定义两个指针反向输出
if(head==null){
retrun null;
}else{
ListNode tmp=null;
while(head!=null){
ListNode p=head.next;
head.next=tmp;
tmp=head;
head=p;
}
retrun tmp;
}
}
1.3输出链表的倒数第k个节点
//分别设置快指针和满指针,快指针先走k步,然后两个指针同时移动直到快指针指向null,返回慢指针
public ListNode findKthToTail(ListNode head,int k){
if(head==null||k<0){
return null;
}
ListNode fast=null;
ListNode slow=null;
while(k>1){
if(fast.next!=null){
fast=fast.next;
}else{
return null;
}
k--;
}
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
1.4寻找两个链表的第一个公共节点
public ListNode findFirstCommonNode(ListNode list1,ListNode list2){
ListNode p1=list1;
ListNode p2=list2;
while(p1!=p2){
p1=(p1!=null?p1.next:list2);
p2=(p2!=null?p2.next:list1);
}
return p1;
}
1.5判断链表是否有环并返回环的入口结点
public ListNode entryOfLoop(ListNode pHead){
//校验参数先
if(pHead==null||pHead.next==null)
return null;
//新建快慢指针
ListNode fast=pHead;
ListNode slow=pHead;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast){
fast=pHead;
while(slow!=fast){
fast=fast.next;
slow=slow.next;
}
if(slow==fast)
return slow;
}
}
return null;
}
1.6 合并两个有序链表
/**
* 合并两个有序递增链表,返回合并链表的头结点,保证单调不减
* 新建一个新的链表头ret来作为合并后的链表,链表的头结点是ret.next
* @param l1
* @param l2
* @return
*/
public static ListNode mergeTwoLists(ListNode l1,ListNode l2){
if (l1==null)
return l2;
if (l2==null)
return l1;
ListNode p1=l1;
ListNode p2=l2;
ListNode ret=new ListNode(0);
ListNode ans=ret;
while (p1!=null&&p2!=null){
if (p1.val>p2.val){
ret.next=p2;
ret=ret.next;
p2=p2.next;
}else {
ret.next=p1;
ret=ret.next;
p1=p1.next;
}
}
if (p1==null&&p2!=null)
ret.next=p2;
if (p2==null&&p1!=null)
ret.next=p1;
return ans.next;
}