无头单向不循环链表的扩展
倒数第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;
}
}