标签:指针 tno while turn image ati 如何 思路 alt
1,如果两个单链表相交,输出相交节点
1 //两链表相交问题
2 class T18{
3 public static class Node{
4 private int value;
5 private Node next;
6 public Node(int value){
7 this.value=value;
8 }
9 }
10 public static Node getNode(Node node1,Node node2){
11 int node1_len = getLen(node1); //获得两个链表的长度
12 int node2_len = getLen(node2);
13 Node longLink=node1_len>node2_len?node1:node2; //确定那个是长的
14 Node shortLink=node1_len<node2_len?node1:node2;
15 int cha=Math.abs(node1_len-node2_len); //得到长度的差值
16 for (int i = 0; i < cha; i++) { //将长的的起点走到与短的相同
17 longLink=longLink.next;
18 }
19 while(longLink.value!=shortLink.value){ //知道两个结点相交
20 longLink=longLink.next;
21 shortLink=shortLink.next;
22 }
23 return longLink;
24 }
25 public static int getLen(Node head){
26 int length=0;
27 while(head!=null){
28 head=head.next;
29 length++;
30 }
31 return length;
32 }
33 }
2,一个链表成环问题
1 //单向链表相交问题:找出环的入口结点
2 class Find{
3 public static class Node{
4 private int value;
5 private Node next;
6
7 public Node(int value) {
8 this.value = value;
9 }
10 }
11
12 public Node judge(Node head){
13 Node n1=head;
14 Node n2=head;
15 while(n1!=null&&n2!=null){
16 n1=n1.next;
17 n2=n2.next.next;
18 if(n1==n2){
19 return n1;
20 }
21 }
22 return null;
23 }
24 public Node find(Node head){
25 int lengh=0;
26 Node judge = judge(head);
27 if(judge==null){
28 return null;
29 }
30 Node temp1=judge;
31 //得到环中结点的个数
32 while(judge.next!=temp1){
33 lengh++;
34 }
35 Node p1=head;
36 for (int i = 0; i <lengh ; i++) {
37 p1=p1.next;
38 }
39 Node p2=head;
40 while(p1!=p2){
41 p1=p1.next;
42 p2=p2.next;
43 }
44 return p1;
45 }
46 }
标签:指针 tno while turn image ati 如何 思路 alt
原文地址:https://www.cnblogs.com/fangtingfei/p/12812867.html