public int insertAtN(int pos, Node newNode) { if (newNode == null || pos <= 0) { System.out.println("Invalid node or position"); return -1; } if (pos == 1) { newNode.next = head; head = newNode; return 1; } Node temp = head; int counter = 1; while (temp.next != null && counter < pos - 1) { temp = temp.next; counter++; } if (counter < pos - 1) { System.out.println("insert position is greater than list length"); return -1; } newNode.next = temp.next; temp.next = newNode; return pos; }
/** * Will add a new item to the start of the deque. Will throw an error if an empty item is passed * through. If this is the first item that has been added to the deque, then this will also set * the last item in the deque to be the first. * * @param item The item to add to the start of the deque */ public void addFirst(Item item) { if (item == null) { throw new NullPointerException("Woah, you can't add nothing"); } Node previousFirst = first; first = new Node(); first.item = item; first.previous = null; if (previousFirst == null) { // This is the first time something has been added to the deque first.next = null; } else { first.next = previousFirst; previousFirst.previous = first; } // Is this the only node in the deque? if (last == null) { last = first; } N++; }
public static void main(String args[]) { head = new Node(3); Node n1 = new Node(5); Node n2 = new Node(11); Node n3 = new Node(2); Node n4 = new Node(7); Node n5 = new Node(9); Node n6 = new Node(33); Node n7 = new Node(1); Node n8 = new Node(8); Node n9 = new Node(156); Node n10 = new Node(10); head.next = n1; n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; n6.next = n7; n7.next = n8; n8.next = n9; n9.next = n10; int k = 3; Node p = ReverseAllKNodes(head, k); print(p); // KthFromEnd(head, k); System.out.println(""); }
// no concurrent read/write is assumed public V put(double key, V value) { if (value == null) throw new NullPointerException(); // not incrementing b's refcnt, so need not release it. Node b = skipListMap.findGrandPredecessor(key); if (b == null) b = head; Node n = b.next; if (n == null) { n = Node.alloc(); n.put(key, value, this); n.next = null; b.next = n; return null; } Node f = n.next; if (f == null) { // put (key,value) into node n Object val = n.put(key, value, this); return (V) val; } else { assert f.len() > 0 && f.first() >= key; if (f.first() == key) { Object val = f.put(key, value, this); return (V) val; } else { Object val = n.put(key, value, this); return (V) val; } } }
public void alternateSplit(Node head) { if (null == head || null == head.next) return; Node current = head.next.next; Node head1 = head; Node head2 = head.next; head1.next = null; head2.next = null; boolean first = true; while (current != null) { if (first) { Node temp = current.next; current.next = null; head1 = Push.pushNode(head1, current); first = false; current = temp; } else { Node temp = current.next; current.next = null; head2 = Push.pushNode(head2, current); first = true; current = temp; } } head1 = ReverseListIterative.reverse(head1); head2 = ReverseListIterative.reverse(head2); System.out.println("List1: "); PrintLinkedList.print(head1); System.out.println(); System.out.println("List2: "); PrintLinkedList.print(head2); }
/** * Swap nodes of the given indices * * @param x * @param y */ public void swapNodes(int x, int y) { Node<T> cursor = head; Node<T> curX = null; Node<T> prevX = null; Node<T> curY = null; Node<T> prevY = null; int position = 0; if (x == y) return; if (cursor != null && x == position) { curX = head; } position++; while (cursor != null && cursor.next != null) { if (x == position) { prevX = cursor; curX = cursor.next; } if (y == position) { prevY = cursor; curY = cursor.next; } position++; cursor = cursor.next; } Node<T> temp = null; if (prevX != null) prevX.next = curY; else head = curY; prevY.next = curX; temp = curY.next; curY.next = curX.next; curX.next = temp; }
/** * Merge Sort Part II - Merge the left and right part while sorting them in order * * @param leftHalfList * @param rightHalfList * @return */ private Node<T> merge(SinglyLL<T> leftHalfList, SinglyLL<T> rightHalfList) { SinglyLL<T> sortedList = new SinglyLL<>(); Node<T> sortedListCursor = null; Node<T> leftCursor = leftHalfList.head; Node<T> rightCursor = rightHalfList.head; if (leftHalfList.head != null && rightHalfList.head != null && leftHalfList.head.data.compareTo(rightHalfList.head.data) < 0) { sortedList.head = leftCursor; leftCursor = leftCursor.next; } else { sortedList.head = rightCursor; rightCursor = rightCursor.next; } sortedListCursor = sortedList.head; while (leftCursor != null && rightCursor != null) { if (leftCursor.data.compareTo(rightCursor.data) <= 0) { sortedListCursor.next = leftCursor; leftCursor = leftCursor.next; } else if (leftCursor.data.compareTo(rightCursor.data) > 0) { sortedListCursor.next = rightCursor; rightCursor = rightCursor.next; } sortedListCursor = sortedListCursor.next; } if (rightCursor == null) sortedListCursor.next = leftCursor; if (leftCursor == null) sortedListCursor.next = rightCursor; return sortedList.head; }
public int get(int key) { if (!cache.containsKey(key)) { return -1; } Node node = cache.get(key); if (node != head) { Node prev = node.prev; Node next = node.next; node.prev = null; node.next = head; head.prev = node; head = node; prev.next = next; if (next == null) { least = prev; } else { next.prev = prev; } } return node.value; }
public void set(int key, int value) { if (least == null) { this.least = new Node(key, value); this.head = this.least; cache.put(key, this.least); } else { if (cache.containsKey(key)) { Node node = cache.get(key); node.value = value; cache.put(key, node); get(key); } else { Node node = new Node(key, value); node.prev = null; node.next = head; head.prev = node; head = node; if (cache.size() == size) { Node prev = least.prev; prev.next = null; least.prev = null; least = prev; cache.remove(least.key); } cache.put(key, node); } } }
// Insert a node at a specific position in a linked list Node InsertSpecific(Node head, int data, int position) { // Will Need to Return Head Node Node trackedHeadNode = head; Node nodeToInsert = new Node(); nodeToInsert.data = data; // Empty List - Returned newly created node or null if (head == null) { return nodeToInsert; } // Inserting a Node ahead of the List if (position == 0) { nodeToInsert.next = head; return nodeToInsert; } // Traverse the Singly Linked List to 1 Position Prior // Stop traversing if you reached the end of the List int currPosition = 0; while (currPosition < position - 1 && head.next != null) { head = head.next; currPosition++; } // Inserting a Node in-between a List or at the end of of a List Node nodeAtPosition = head.next; head.next = nodeToInsert; head = head.next; head.next = nodeAtPosition; return trackedHeadNode; }
// Delete a node Node Delete(Node head, int position) { // Complete this method Node trackedHeadNode = head; int currPosition = 0; if (position == 0 && head.next == null) { return null; } if (position == 0) { head = head.next; return head; } while (currPosition < position - 1 && head.next != null) { head = head.next; currPosition++; } Node tempNode = head.next; head.next = null; if (tempNode.next == null) { return trackedHeadNode; } head.next = tempNode.next; return trackedHeadNode; }
public Item dequeue() // delete and return a random item { if (isEmpty()) { throw new java.util.NoSuchElementException("RandomizedQueue is empty"); } int index = StdRandom.uniform(0, size); Node node = findNode(index); Item item = node.item; Node prevnode = node.prev; Node nextnode = node.next; if (prevnode != null) { prevnode.next = nextnode; } else { first = nextnode; } if (nextnode != null) { nextnode.prev = prevnode; } else { last = prevnode; } node.item = null; node.next = null; node.prev = null; size--; return item; }
void add(int num) { Node newNode = new Node(); newNode.contents = num; if (first == null) { first = newNode; return; } assert first != null; if (first.contents >= num) { first.previous = newNode; newNode.next = first; first = newNode; return; } assert first.contents < num; Node tmp = first; while (tmp.contents < num && tmp.next != null) tmp = tmp.next; assert tmp != null; if (tmp.contents < num && tmp.next == null) { tmp.next = newNode; newNode.previous = tmp; } else { assert tmp.contents >= num; assert tmp.previous.contents < num; newNode.previous = tmp.previous; newNode.previous.next = newNode; newNode.next = tmp; newNode.next.previous = newNode; } }
/** * Remove first occurrence of an object with the same value as obj * * @param object with equal value as the one to remove from the list * @return true if an object is removed, false otherwise */ public boolean remove(E obj) { if (tail == null) return false; Node<E> list = tail.next; // delete tail if only node if (size == 1 && (tail.compare(obj))) { tail = null; size--; return true; } // delete head node if (list.compare(obj)) { tail.next = list.next; size--; return true; } // delete middle nodes while (list.next != tail) { if (list.next.compare(obj)) { // remove node from list list.next = list.next.next; size--; return true; } list = list.next; } // delete tail node if (tail.compare(obj)) { list.next = tail.next; tail = list; size--; return true; } return false; }
// 插入节点 public DoubleLink insert(int ind, int x) throws Exception { // 初始化没有节点 if (ind1 == 0 && ind == 0) { addhead(x); } // 节点>=1;插入位置=0 else if (ind1 >= 1 && ind == 0) { addhead(x); } // 节点>=2;插入位置位置不在头尾 else if (ind1 >= 2 && ind >= 1 && ind <= ind1 - 1) { Node nn = new Node(x); Node temp = head; for (int i = 1; i <= ind - 1; i++) { temp = temp.next; } temp.next.prior = nn; nn.next = temp.next; nn.prior = temp; temp.next = nn; ind1++; } // 节点>=1;插入位置在尾部 else if (ind1 == ind && ind1 >= 1) { Node nn = new Node(x); tail.next = nn; nn.prior = tail; nn.next = null; tail = nn; ind1++; } // 插入位置和节点不匹配 else { throw new Exception("链表长度和插入位置不匹配."); } return this; }
public Node(int nodeType, Node left, Node right) { type = nodeType; first = left; last = right; left.next = right; right.next = null; }
public void insert(Node newNode, int index) { if (index > size || index < 0) { throw new VectorIndexOutOfBoundsException(); } Node current = null; try { current = getNode(index); } catch (VectorIndexOutOfBoundsException e) { current = head; } if (head != null) { newNode.next = current; newNode.prev = current.prev; current.prev.next = newNode; current.prev = newNode; } else { newNode.next = newNode; newNode.prev = newNode; } if (index == 0) { head = newNode; } ++size; }
public void removeChild(Node child) { Node prev = getChildBefore(child); if (prev == null) first = first.next; else prev.next = child.next; if (child == last) last = prev; child.next = null; }
/** * Swap nodes containing the data provided. * * @param x * @param y */ public void swapNodes(T x, T y) { Node<T> cursor = head; Node<T> curX = null; Node<T> prevX = null; Node<T> curY = null; Node<T> prevY = null; if (cursor != null && cursor.data.equals(x)) { curX = head; } while (cursor != null && cursor.next != null) { if (cursor.next.data.equals(x)) { prevX = cursor; curX = cursor.next; } if (cursor.next.data.equals(y)) { prevY = cursor; curY = cursor.next; } cursor = cursor.next; } Node<T> temp = null; if (prevX != null) prevX.next = curY; else head = curY; prevY.next = curX; temp = curY.next; curY.next = curX.next; curX.next = temp; }
public void replaceChildAfter(Node prevChild, Node newChild) { Node child = prevChild.next; newChild.next = child.next; prevChild.next = newChild; if (child == last) last = newChild; child.next = null; }
/** * Add an element. * * @param item element to add * @param msg * @return true if element was not there already */ @Override public boolean add(Integer item, String msg) { int key = item.hashCode(); while (true) { Node pred = this.head; Node curr = pred.next; while (curr.key <= key) { pred = curr; curr = curr.next; } pred.lock(); curr.lock(); try { if (validate(pred, curr)) { if (curr.key == key) { System.out.println(msg + "Adding " + item + " : cannot add same item twice."); return false; } else { Node entry = new Node(item); entry.next = curr; pred.next = entry; System.out.println(msg + "Adding : " + item); return true; } } } finally { pred.unlock(); curr.unlock(); } } }
public static void main(String[] args) { // TODO Auto-generated method stub Node head1 = null; Node last1 = null; Node head2 = null; Node last2 = null; Scanner in = new Scanner(System.in); int num1 = in.nextInt(); for (int i = num1; i > 0; i--) { if (head1 == null) { head1 = new Node(in.nextInt(), in.nextInt()); } else { head1.next = new Node(in.nextInt(), in.nextInt()); head1 = head1.next; } } int num2 = in.nextInt(); for (int i = num2; i > 0; i--) { if (head2 == null) { head2 = new Node(in.nextInt(), in.nextInt()); last2 = head2; } else { last2.next = new Node(in.nextInt(), in.nextInt()); last2 = last2.next; } } in.close(); display(head1); display(head2); display(PolyAdd(head1, head2)); }
/** * Add an element. * * @param item element to add * @param msg * @return true if element was not there already */ @Override public boolean add(Integer item, String msg) { int key = item.hashCode(); head.lock(); Node pred = head; try { Node curr = pred.next; curr.lock(); try { while (curr.key < key) { pred.unlock(); pred = curr; curr = curr.next; curr.lock(); } if (curr.key == key) { System.out.println(msg + "Adding " + item + " : cannot add same item twice."); return false; } Node newNode = new Node(item); newNode.next = curr; pred.next = newNode; System.out.println(msg + "Adding : " + item); return true; } finally { curr.unlock(); } } finally { pred.unlock(); } }
private static Node partition(Node head, int val) { Node less = null; Node p1 = less; Node great = null; Node p2 = great; while (head != null) { Node temp = head.next; head.next = null; if (head.getData() < val) { if (less == null) { less = head; p1 = less; } else { p1.next = head; p1 = p1.next; } } else { if (great == null) { great = head; p2 = great; } else { p2.next = head; p2 = p2.next; } } head = temp; } p1.next = great; return less; }
public static Node reverseList(Node Head) { Node node = Head; Node reverse = null; Node returnReverse = null; while (node != null) { Node prev = node; while (node.next != null) { prev = node; node = node.next; } if (reverse == null) { reverse = node; returnReverse = reverse; } else { reverse.next = node; reverse = reverse.next; } prev.next = null; node = Head; if (prev == node) { // 노드 삽입 reverse.next = node; node = null; } } return returnReverse; }
public boolean insert(Object item) { int key = item.hashCode(); head.lock(); Node pred = head; try { Node curr = pred.next; curr.lock(); try { while (curr.key < key) { pred.unlock(); pred = curr; curr = curr.next; curr.lock(); } if (curr.key == key) { return false; } Node newNode = new Node(item); newNode.next = curr; pred.next = newNode; return true; } finally { curr.unlock(); } } finally { pred.unlock(); } }
public static Node ordersort(Node head, Node waitforsort) { Node p = head; Node newhead = head; Node temp = waitforsort; while (p.expo < temp.expo) { if (p.next == null) { p.next = temp; return newhead; } if (p.next.expo > temp.expo) { temp.next = p.next; p.next = temp; return newhead; } p = p.next; } if (p.expo == temp.expo) { p.coeff = temp.coeff + p.coeff; return newhead; } if (p.expo > temp.expo) { temp.next = p; newhead = temp; return newhead; } return newhead; }
// Задание 2.2.3 public void combineLists(List<Item> list2) { Node l1 = this.head; Node l2 = list2.head; this.push(l2.data); // добавить эл-т из второго списка в начало первого l2 = l2.next; int position = 1; // позиция в первом списке while (l2 != null && l1 != null) { if (position % 2 != 0) { // если нечётная позиция Node newNode = new Node(); // вставляемый узел newNode.data = l2.data; // вставка в первый список после текущего newNode.next = l1.next; l1.next = newNode; l1 = l1.next; l2 = l2.next; position++; } else { // если позиция чётная l1 = l1.next; position++; } } if (l2 != null && l1 == null) { while (l2 != null) { this.addLast(l2.data); l2 = l2.next; } } }
// T = LITERAL | '${' V '}' private Node T() throws ScanException { Token t = getCurentToken(); switch (t.type) { case LITERAL: advanceTokenPointer(); return new Node(Node.Type.LITERAL, t.payload); case CURLY_LEFT: advanceTokenPointer(); Node inner = E(); Token right = getCurentToken(); expectCurlyRight(right); advanceTokenPointer(); Node curlyLeft = new Node(Node.Type.LITERAL, CoreConstants.LEFT_ACCOLADE); curlyLeft.next = inner; Node curlyRightNode = new Node(Node.Type.LITERAL, CoreConstants.RIGHT_ACCOLADE); if (inner == null) curlyLeft.next = curlyRightNode; else appendNode(inner, curlyRightNode); return curlyLeft; case START: advanceTokenPointer(); Node v = V(); Token w = getCurentToken(); expectCurlyRight(w); advanceTokenPointer(); return v; default: return null; } }
public Node reverseList() { if (head == null || head.next == null) return head; if (head.next.next == null) { head.next.next = head; head = head.next; head.next.next = null; } Node n1 = head; Node n2 = head.next; Node n3 = head.next.next; n1.next = null; while (n2.next != null) { n2.next = n1; n1 = n2; n2 = n3; n3 = n3.next; } n2.next = n1; head = n2; return head; }