寻找链表的结点
1.尋找鏈表的中間結點
public Node middleNode(Node head) {if(head==null){return head;}Node slow=head;Node fast=head;while(fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;}return slow;}2.尋找鏈表倒數第k個結點
方法一:快慢指針
public Node FindKthToTail1(Node head,int k){//輸入一個鏈表,輸出該鏈表中倒數第k個結點。if(k<=0||head==null){throw new ArrayIndexOutOfBoundsException("k的值不合法k="+k);}Node slow=head;Node fast=head;//先讓fast走到第k個結點;for(int i=0;i<k;i++){if(fast.next!=null) {fast = fast.next;}elsefast=null;}while(fast!=null){slow=slow.next;fast=fast.next;}return slow;}方法二:倒數第k就是size-k個結點
public Node FindKthToTail2(Node head,int k){Node current =head;int count=0;while(current!=null){count++;current=current.next;}if(k<=0||k>count){throw new ArrayIndexOutOfBoundsException("k的值不合法k="+k);}Node tmp=head;for(int i=0;i<count-k;i++){if(tmp.next!=null)tmp=tmp.next;}return tmp;}總結
- 上一篇: 使用Java实现矩形 平行四边形 等腰三
- 下一篇: MIKE水动力笔记7_实测数据与模型输出