- public class ListNode {
- int data;// 当前节点的值
- ListNode next = null;// 是指向下一个节点的指针 / 引用
- public ListNode(int data){
- this.data = data;
- }
- }
- public class DeleteListNode {
- public static ListNode delete(ListNode head){
- // 链表为空
- if(head == null){
- return null;
- }
- ListNode odd = head;
- // 链表长度为偶数
- if(length(head)%2 == 0){
- while (odd.next != null && odd.next.next != null){
- odd.next = odd.next.next;
- odd = odd.next;
- if(odd.next.next == null && odd.next != null){
- odd.next=null;
- }
- }
- }
- // 链表长度为奇数
- if(length(head)%2 == 1){
- while (odd.next != null && odd.next.next != null){
- odd.next = odd.next.next;
- odd = odd.next;
- }
- }
- // 返回头结点
- return head;
- }
- // 返回链表长度
- private static int length(ListNode node){
- int length = 0;
- while (node != null){
- node = node.next;
- length++;
- }
- return length;
- }
- // 打印链表
- private static void print(ListNode node) {
- System.out.print(node.data);
- if (node.next != null){
- print(node.next);
- }
- }
- public static void main(String[] args){
- ListNode node1 = new ListNode(1);
- ListNode node2 = new ListNode(2);
- ListNode node3 = new ListNode(3);
- ListNode node4 = new ListNode(4);
- ListNode node5 = new ListNode(5);
- ListNode node6 = new ListNode(6);
- ListNode node7 = new ListNode(7);
- ListNode node8 = new ListNode(8);
- ListNode node9 = new ListNode(9);
- node1.next = node2;
- node2.next = node3;
- node3.next = node4;
- node4.next = node5;
- node5.next = node6;
- node6.next = node7;
- node7.next = node8;
- node8.next = node9;
- System.out.println("删除偶数节点前, 链表为:");
- print(node1);
- delete(node1);
- System.out.println("\n 删除偶数节点后, 链表为:");
- print(node1);
- }
- }
来源: http://www.bubuko.com/infodetail-2974451.html