一、删除中间节点:
要求:删除中间节点的函数
思路:本题并不是让你取得中间位节点,而是删除,所以关键是取得中间点的前一位。正常取中值用快慢指针,head.next,与,head.next.next。所以我们需要把慢指针前移一位,就变成了head
public class text {
public Node deleteMid(Node head) {
if(head==null||head.next==null) {
return head;
}
if(head.next.next==null) {
return head.next; //以上两个分别写明了链表存在0个,1个,2个元素的特殊情况
}
Node pre = head; //正常找中值应该是head.next与head.next.next,但是此处我们需要有中值的前一位
Node cur = head.next.next; //所以慢指针要前移一位,变成head
while(cur.next!=null&&cur.next.next!=null) {
cur = cur.next.next;
head = head.next;
}
pre.next = pre.next.next; //当cur到达最后时,pre为中间值的前一位,直接跳过一位即可删除
return head;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
二、删除a/b处的节点
要求:给两个整数a,b,实现删除a/b处节点的函数。r = a/b(r<=1),若r=0,不删除;其他r的值向上取整,比如r在范围(2/5,3/5]中,取3,删除第三个节点。
思路:首先涉及到一个求链表长度,一次遍历,然后是求删第几个,涉及到一个向上取整的运算。最后依旧是注意要取得r前一个的元素,才能删除r
public class text {
public Node deleteR(Node head,int a,int b) {
if(a<1||a>b) {
return head;
}
int len = 0;
Node cur = head;
while(cur!=null) {
len++;
cur = cur.next;
}
int n = 0;
n = (int)Math.ceil((double)(a*len)/(double) b); //Math.ceil(double a),为向上取整,注意返回也为double,要强制转换
if(n==1) {
head = head.next;
}
n--; //直接只计数n-1个就是要删除的那位的前一位
if(n>1) {
cur = head;
while(n>0) {
cur = cur.next; //计数n-1个
}
cur.next = cur.next.next;
}
return head;
}
}