Cracking the coding interview--Q2.3

题目

原文:

Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
EXAMPLE
Input: the node ‘c’ from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a->b->d->e

译文:

实现一个算法去删除一个单链表中间的节点,只给出指向那个节点的指针

例如

输入:链表a->b->c->d->e中的节点c

结果:不用返回什么,只是新的链表变为a->b->d->e

解答

注意题目只给出要删除的节点,代码如下:

class Q2_3{

	public static boolean deleteNode(Node n) {
		if (n == null || n.next == null) {
			return false; // Failure
		}
		Node next = n.next;
		n.data = next.data;
		n.next = next.next;
		return true;
	}
	
	public static void main(String[] args){
		int[] data=new int[]{1,2,3,2,5};
		
		LinkList ll=new LinkList();
		for(int i=0;i<data.length;i++){
			ll.add(data[i]);
		}
		
		//ll.delete(3);
		//ll.print();
		
		deleteNode(ll.head.next.next);
		ll.print();
	}
}

class Node{
	public Object data;
	public Node next;
	
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public Node getNext() {
		return next;
	}
	public void setNext(Node next) {
		this.next = next;
	}
}	
	
class LinkList{
	public Node head;
    public Node tail;
    private int size;
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
    
	public void add(Object i){//在链表结尾插入节点
		Node newnode = new Node();
		newnode.setData(i);
		if(head == null){
			head = newnode;
			tail = newnode;
			size ++ ;
		}
		else {
			tail.setNext(newnode);
			tail = newnode;
			size ++ ;
		}
	}
	//删除节点值为i的节点
	public void delete(Object i){
		if(head == null){
			System.out.println("链表为空");
			return;
		}
		Node temp = head;
		while(temp.getNext().getData() != i){
			temp= temp.getNext();
		}
		if(temp == null){
			System.out.println("没有该节点");
			return;
		}
		temp.setNext(temp.getNext().getNext());
		size--;
	}
	
	public void print(){
		if(head == null){
			System.out.println("链表为空");
			return;
		}
		Node temp = head;
		while(temp.getNext()!= null){
			System.out.println(temp.getData().toString());
			temp=temp.getNext();
		}
		System.out.println(temp.getData().toString());
	}
}

---EOF---

你可能感兴趣的:(Cracking the coding interview--Q2.3)