剑指offer-13-O(1)时间删除链表结点-java

题目及测试

package sword013;
/*问题描述:给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
*/


public class main {
	
	
	public static void main(String[] args) {
		
		LinkList a=new LinkList(1);
		a.addLast(2);
		a.addLast(5);

		a.printList();		
		test(a.first,a.first.next.next);
		
	}
		 
	private static void test(ListNode ito,ListNode ito2) {
		Solution solution = new Solution();
		ListNode rtn;
		long begin = System.currentTimeMillis();
		System.out.println();
		//开始时打印数组
		
		rtn=solution.deleteNode(ito,ito2);//执行程序
		long end = System.currentTimeMillis();	
		
		rtn.printNodeToEnd();
		
		//System.out.println(":rtn" );
		//System.out.print(rtn);
		System.out.println();
		System.out.println("耗时:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

解法1(成功)

如果删除节点是头结点,返回头结点的next
如果删除节点是中间结点,删除节点的值设置为next的值,然后删除节点的next指向next的next
如果删除节点是尾节点,从头开始遍历,设置删除节点的前一个节点的next为null

package sword013;



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteNode(ListNode head, ListNode deListNode) {
    	if(head == null) {
    		return null;
    	}
    	if(head == deListNode) {
    		ListNode next = head.next;
    		head.next = null;
    		return next;
    	}
    	// 删除最后一个节点
    	if(deListNode.next == null) {
    		ListNode now =head;
    		while(now.next != deListNode) {
    			now = now.next;
    		}
    		now.next = null;
    	}
    	// 删除中间节点
    	else {
    		ListNode next = deListNode.next;
    		deListNode.val = next.val;
    		deListNode.next = next.next;
    		next.next = null;
    	} 	
    	return head;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值