算法练习LeetCode初级算法之链表

  • 删除链表中的节点

/**

* Definition for singly-linked list.

* public class ListNode {

* int val;

* ListNode next;

* ListNode(int x) { val = x; }

* }

*/

class Solution {

public void deleteNode(ListNode node) {

node.val=node.next.val;

node.next=node.next.next;

}

}

  • 删除链表的倒数第N个节点

  • 两次遍历算法

    class Solution {

    public ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode dummy=new ListNode(0);

        dummy.next=head;

        int length=0;

        ListNode p=head;

        while (p!=null) {

                length++;

                p=p.next;

            }

        ListNode first=dummy;

        length-=n;

        while (length>0) {

                length--;

                first=first.next;

            }

        first.next=first.next.next;

        return dummy.next;

    }

    }

  • 一次遍历算法

    class Solution {

        public ListNode removeNthFromEnd(ListNode head, int n) {

         ListNode dummy = new ListNode(0);

         dummy.next = head;

         ListNode first = dummy;

         ListNode second = dummy;

         // Advances first pointer so that the gap between first and second is n nodes apart

         for (int i = 1; i <= n + 1; i++) {

         first = first.next;

         }

         // Move first to the end, maintaining the gap

         while (first != null) {

         first = first.next;

         second = second.next;

         }

         second.next = second.next.next;

         return dummy.next;

        }

    }

  • 反转链表

我的解法:利用Linklist比较好理解

class Solution {

public ListNode reverseList(ListNode head) {

        LinkedList<Integer> list=new LinkedList<>();

        for(ListNode x=head;x!=null;x=x.next) {

            list.add(x.val);

        }

        for(ListNode x=head;x!=null;x=x.next) {

            x.val=list.removeLast();

        }

    return head;

}

}

 

猜你喜欢

转载自www.cnblogs.com/GavinYGM/p/10333776.html