Java 链表删除倒数第 k 个节点测试用例
import org.junit.Test;
public class RemoveKthFromEndTest {
@Test
public void testRemove() {
RemoveKthFromEnd.ListNodeE head = new RemoveKthFromEnd().new ListNodeE(1);
head.next = new RemoveKthFromEnd().new ListNodeE(2);
head.next.next = new RemoveKthFromEnd().new ListNodeE(3);
head.next.next.next = new RemoveKthFromEnd().new ListNodeE(4);
head.next.next.next.next = new RemoveKthFromEnd().new ListNodeE(5);
RemoveKthFromEnd removeKthFromEnd = new RemoveKthFromEnd();
RemoveKthFromEnd.ListNodeE result = removeKthFromEnd.remove(head, 2);
while (result != null) {
System.out.print(result.val + ' ');
result = result.next;
}
}
}
public class RemoveKthFromEnd { public class ListNodeE{ int val; ListNodeE next; public ListNodeE(int x){ val = x; } } public ListNodeE remove(ListNodeE head,int k){ ListNodeE dummy = new ListNodeE(0);//定义一个虚拟头节点 dummy.next = head; ListNodeE front = dummy , behind = dummy; while(front !=null && k > 0){ front = front.next; k--; } while(front != null){ front = front.next; behind = behind.next; } behind.next = behind.next.next; return dummy.next; } }
原文地址: https://www.cveoy.top/t/topic/pYUn 著作权归作者所有。请勿转载和采集!