Solutions and Summay for Linked List Naive and Easy Questions

时间:2024-07-25 23:36:20

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