前言
基于链表的操作比较多,希望通过一系列的实战操作,加深对链表的理解和应用。每日更新两题,希望学习的小伙伴关注一波,评论区欢迎讨论交流。
今日份练习
打印两个有序链表的公共部分
实现原理
既然是有序链表,选择从两个链表的头部开始比较。比较两个链表的当前元素,如果链表的当前元素小,则指针往后移。如果链表的当前元素值相等,则打印并将指针向后移动一位。
代码实现
class Node{
int data;
Node next;
public Node(int data){
this.data=data;
this.next=null;
}
}
public class LinkedListDemo1 {
private Node headA;
private Node headB;
static void printSameNode(Node headA,Node headB){
while(headA!=null&&headB!=null){
if(headA.data<headB.data){
headA=headA.next;
}else if(headA.data>headB.data){
headB=headB.next;
}else{
System.out.println(headA.data);
headA=headA.next;
headB=headB.next;
}
}
}
public static void main(String[] args) {
Node headA=new Node(1);
Node currentA=headA;
for(int i=2;i<5;i++){
currentA.next=new Node(i);
currentA=currentA.next;
}
Node headB=new Node(3);
Node currentB=headB;
for(int i=4;i<8;i++){
currentB.next=new Node(i);
currentB=currentB.next;
}
printSameNode(headA,headB);
}
}