JAVA初窺-DAY12
- 無頭單向不回圈鏈表的擴展
- 倒數第K
- 鏈表排序
- 判斷回文
- 判斷有環
- 判斷有環延續
- 清除重復
無頭單向不回圈鏈表的擴展
倒數第K
輸出倒數第K個節點
public Node back(int k){//輸出倒數第K個節點
Node slow = this.head;
Node fast = this.head;
if (k<1||k>size){
System.out.println("請輸入正確的K");
return null;
}
for (;k>0;k--){
fast=fast.next;
}
for (;fast != null;){
fast=fast.next;
slow=slow.next;
}
return slow;
}
鏈表排序
小于x的放前面,其余的放后面,
public void sort(int x){//排序:小于x的放前面,其余的放后面
if (head ==null){
return;
}
Node af = null;
Node ae = null;
Node bf = null;
Node be = null;
Node cur = this.head;
for (;cur !=null;cur=cur.next){
if (cur.val < x){
if (af == null){
af = cur ;
ae = cur ;
}else {
ae.next = cur;
ae = cur;
}
}else {
if (bf == null){
bf = cur ;
be = cur ;
}else {
be.next = cur;
be = cur;
}
}
}
be.next=null;
if (af == null){
this.head = bf;
return;
}
if (bf == null){
ae.next = null;
this.head = af;
return;
}
ae.next=bf;
return;
}
判斷回文
回文結構:12321、123321、181等
public boolean plalindrome(){
Node prev =midNode();
Node cur = prev.next;
Node curNext = cur.next;
for (;curNext!=null;){
cur.next = prev;
prev = cur;
cur = curNext;
curNext = curNext.next;
}
cur.next = prev;
prev = this.head;
for (;prev != cur && prev.next != cur ;){
if (cur.val != prev.val){
return false;
}
prev=prev.next;
cur = cur.next;
}
if (cur.val != prev.val){
return false;
}
return true;
}
判斷有環
public boolean ring(){
Node fast = this.head;
Node slow = this.head;
for (;fast!=null && fast.next!=null;){
fast=fast.next.next;
slow=slow.next;
if (slow == fast){
break;
}
}
if (fast == null || fast.next==null){
return false;
}
return true;
}
判斷有環延續
判斷有環并 輸出環的入口節點
public int ringB(){
Node fast = this.head;
Node slow = this.head;
for (;fast!=null && fast.next!=null;){
fast=fast.next.next;
slow=slow.next;
if (slow == fast){
break;
}
}
if (fast == null || fast.next==null){
return -1;
}
fast = this.head;
for (;fast != slow;){
fast = fast.next;
slow = slow.next;
}
return slow.val;
}
清除重復
有序鏈表清除重復內容,且不保留重復內容
public void clear() {
Node cur = this.head;
for (;cur.next!=null;){
if (cur.val == cur.next.val){
del(cur.val);
}
cur=cur.next;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277137.html
標籤:其他
上一篇:Java 與 動態規劃
下一篇:web簡易視頻聊天室+媒體流插入
