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

不使用哑结点

100.00%
99%
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
   public static ListNode removeNthFromEnd(ListNode head, int n) {
        //统计head的长度
        ListNode q=new ListNode();
        ListNode p = head;
        int count=0;
        //计算长度
        while(p!=null){
            p=p.next;
            count++;
        }
        //控制n在1和count之间
       // if(n>=1&&n<=count){
            //删除head,且链表非空,,,,,1 <= count <= 30
            if(n==count&&count>1){
                head=head.next;
                return head;
            }
            if(n==count&&count==1){
                head=head.next;
                return head;
            }
            //不会删到头,返回head
            if(n<count){
                ListNode p1 = head;
                int count0=0;
                while(p1!=null){

                    count0=count0+1;

                    if(count0==count-n) {
                        p1.next = p1.next.next;
                        break;
                    }

                    p1=p1.next;
                }
                return head;
            }

    // }
return q;
     }
}

使用哑结点:链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        int length = getLength(head);
        ListNode cur = dummy;
        for (int i = 1; i < length - n + 1; ++i) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        ListNode ans = dummy.next;
        return ans;
    }

    public int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            ++length;
            head = head.next;
        }
        return length;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/qq_41557627/article/details/114365627
今日推荐