zoukankan      html  css  js  c++  java
  • Solutions and Summay for Linked List Naive and Easy Questions

    1.Remove Linked List Elements

    package linkedlist;
    /*
     * Question: Remove all elements from a linked list of integers that have value val.
     */
    public class RemoveLinkedListElements {
    
        /**
         * @param head a ListNode
         * @param val an integer
         * @return a ListNode
         */
        public static ListNode removeElements(ListNode head, int val) {
            // Write your code here
        	ListNode dummy = new ListNode(-1);
        	ListNode cur = dummy;
        	dummy.next = head;
        	while(cur.next != null){
        		if(cur.next.val == val){
        			cur.next = cur.next.next;
        		}
        		else{
        			cur = cur.next;
        		}
        	}
        	return dummy.next;
        }
    }
    

    2.Add Two Numbers

    3.Delete Node in the Middle of Singly Linked List

    4.Insertion Sort List

    5.Merge Two Sorted Lists

    6. Nth to Last Node in List

    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */ 
    public class Solution {
        /**
         * @param head: The first node of linked list.
         * @param n: An integer.
         * @return: Nth to last node of a singly linked list. 
         */
        ListNode nthToLast(ListNode head, int n) {
            // write your code here
            ListNode dummy = new ListNode(0);
          dummy.next = head;
          ListNode walker = dummy;
          ListNode runner = dummy;
          while(runner.next != null && n>0){
              runner = runner.next;
              n--;
          }
          while(runner.next != null){
              runner = runner.next;
              walker = walker.next;
          }
          return walker.next;
      }
    }
    

      

    7.Partition List

    8.Remove Duplicates from Sorted List

    9.Remove Nth Node From End of List

    10.Reverse Linked List

    11.Swap Nodes in Pairs

  • 相关阅读:
    linux 防火墙相关
    .net安装windows服务和生产webservice
    linq小实例
    C# DataTable 总结
    document对象
    结对-四则运算-开发过程
    课后作业-阅读任务-阅读笔记-1
    课后作业-阅读任务-阅读提问-2
    课后作业-阅读任务-阅读提问-3
    团对-象棋游戏-开发环境搭建过程
  • 原文地址:https://www.cnblogs.com/heylinart/p/7009104.html
Copyright © 2011-2022 走看看