您的位置:首页 > 其它

删除链表的倒数第K个节点(每日一道算法题)

2017-11-22 11:20 253 查看

单向链表,删除它的倒数第K个节点

//节点类
package LinkedList;

/**
* @author:MindMrWang
*2017年11月22日
*:function:链表节点
*/
public class Node {
public int value;
public Node next;
public Node() {

}
public Node(int data) {
this.value = data;
}

}


public static Node remove(Node head,int k) {
if(head==null||k<1) {//当head为空或者K<1,说明没有倒数第K个节点。
throw new RuntimeException("your LinkedList has none the last k Node");
}
Node cur = head;
while(cur != null) {//从第一个节点开始遍历,若不为空,k--
k--;
cur = cur.next;
}

if(k>0) {
throw new RuntimeException("your LinkedList has none the last k Node");
}

if(k==0) {
head = head.next;//如果k为零,那么倒数第k个元素就是头结点,所以将头结点去除,将head指向head.next
}

if(k<0) {//当K小于零的时候我们想要删除倒数第k个节点,就要知道第N-k个节点(倒数第K个节点的前一个节点)
cur = head;//第一次遍历cur位置改变了,所以要重新赋值
while(++k != 0) {//我们第一次遍历的时候K为k-N,它和N-k为相反数,所以将节点进行第二次从头结点遍历
cur = cur.next;   //每次遍历加1,当它K为0的时候他就移动到了N-k的位置不用
}
cur.next = cur.next.next;
}

return head;

}


双向链表,删除它的倒数第K个节点

package LinkedList;

/**
* @author:MindMrWang
*2017年11月22日
*:function:双向节点
*/
public class DoubleNode {
int value;
DoubleNode last;
DoubleNode next;
public DoubleNode(int data) {
this.value = data;
}
}


//这个是双向链表的删除方法,大体思路和上面相同
public static DoubleNode remove2(DoubleNode head,int k) {
if(head==null||k<1) {//当head为空或者K<1,说明没有倒数第K个节点。
throw new RuntimeException("your LinkedList has none the last k Node");
}

DoubleNode cur = head;
while(cur != null) {//从第一个节点开始遍历,若不为空,k--
k--;
cur = cur.next;
}

if(k>0) {
throw new RuntimeException("your LinkedList has none the last k Node");
}

if(k==0) {
head = head.next;
head.last = null;
}

if(k<0) {
cur = head;
while(++k!=0) {
cur = cur.next;
}
cur.next = cur.next.next;
if(cur.next!=null) {
cur.next.next = cur;
}
}

return head;

}


参数书籍《程序员代码面试指南》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐