16.11.5

来源:互联网 发布:苹果怎么连不上4g网络 编辑:程序博客网 时间:2024/06/06 05:17

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6 Return:
1 –> 2 –> 3 –> 4 –> 5

分析:删除链表中特定值的链表节点

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeElements(ListNode head, int val) {        //当头指针为空时,返回null        if(head==null)return null;        //创建一个慢的指针,指向head节点        ListNode slow=new ListNode(0);        slow.next=head;        //标记头指针的位置        ListNode record=slow;        //创建一个快指针指向头结点        ListNode fast=head;        while(fast!=null){            if(fast.val==val){                //如果快指针指向的节点val与给定的值相等,则将其删除                slow.next=fast.next;                fast=fast.next;            }else{                //否则继续向后移动                fast=fast.next;                slow=slow.next;            }        }        //返回头指针        return record.next;    }}

206. Reverse Linked List

Reverse a singly linked list.
分析:将一个链表原地逆转

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseList(ListNode head) {        //当头指针为空时返回null        if(head==null)return null;        //创建一个新的节点用来存放逆序的链表        ListNode L=new ListNode(0);        //获取原链表的头结点        ListNode p=head;        ListNode temp=null;        L.next=null;        while(p!=null){            //先将下一个节点给temp保存,p节点用于实现头插法            temp=p.next;            //头插法            p.next=L.next;            L.next=p;            p=temp;        }        //返回头结点        return L.next;    }}

204. Count Primes

Description:
Count the number of prime numbers less than a non-negative number, n.
分析:返回n范围内素数的个数

public class Solution {    public int countPrimes(int n) {        int[] a=new int[n+1];        int count=0;        a[0]=0;        if(n!=0)a[1]=0;        for(int i=2;i<n;i++){            a[i]=1;        }        //1代表该索引是素数        for(int i=2;i*i<=n;i++){            if(a[i]==1){                for(int j=i*2;j<=n;j=i+j){                    if(j%i==0){                        //j不是素数                        a[j]=0;                    }                }            }        }        //统计素数的个数        for(int i=0;i<n;i++){            if(a[i]==1){                count++;            }        }        return count;    }}
0 0
原创粉丝点击