3.4 从无头链表中删除节点

3.4 从无头链表中删除节点

基础问题

假设有一个没有头指针的单链表,一个指针指向中间的一个节点,不是第一个节点,也不是最后一个节点,删除该节点

扩展问题

给你一个链表,只遍历一次,在原地翻转链表

class Test{
	public static class ListNode{
		int val;
		ListNode next;
		ListNode(int x){val = x;}
	}
	public static void main(String[] args) {
		
	}
	// 从无头节点单链表中删除节点
	public void deleteListNode(ListNode node){
		if(node == null) return;
		node.val = node.next.val;
		node.next = node.next.next;
	}
	// 翻转链表
	public static ListNode reverseList(ListNode head){
		if(head == null ||  head.next == null) return head;
        ListNode dummy = new ListNode(0);
        ListNode pre = head;
        ListNode cur = head.next;
        dummy.next = null;
        while(pre != null){
            pre.next = dummy.next;
            dummy.next = pre;
            pre = cur;
            if(cur != null)cur=cur.next;
        }
        return dummy.next;
	}

}
posted @ 2020-11-18 15:50  BOTAK  阅读(130)  评论(0)    收藏  举报