`
Copperfield
  • 浏览: 261059 次
  • 性别: Icon_minigender_1
  • 来自: 上海
博客专栏
C407adc3-512e-3a03-a056-ce4607c3a3c0
java并发编程陷阱
浏览量:25213
社区版块
存档分类

单链表反转(Singly Linked Lists in Java)

 
阅读更多
package dsa.linkedlist;

public class Node<E>{
 E data;
 Node<E> next;
}
 
package dsa.linkedlist;

public class ReverseLinkedListRecursively {

	public static void main(String args[]) {
		ReverseLinkedListRecursively reverser = new ReverseLinkedListRecursively();
		SinglyLinkedList<Integer> originalList = reverser.getLabRatList(10);
		System.out.println("Original List : " + originalList.toString());
		originalList.start = reverser.reverse(originalList.start);
		System.out.println("Reversed List : " + originalList.toString());
	}

	public Node<Integer> reverse(Node<Integer> list) {
		if (list == null || list.next == null)
			return list;
		Node<Integer> nextItem = list.next;
		list.next = null;
		Node<Integer> reverseRest = reverse(nextItem);
		nextItem.next = list;
		return reverseRest;
	}

	private SinglyLinkedList<Integer> getLabRatList(int count) {
		SinglyLinkedList<Integer> sampleList = new SinglyLinkedList<Integer>();
		for (int i = 0; i < count; i++) {
			sampleList.add(i);
		}
		return sampleList;
	}
}
/*
 * SAMPLE OUTPUT Original List : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Reversed List : 9,
 * 8, 7, 6, 5, 4, 3, 2, 1, 0
 */
 
package dsa.linkedlist;

/**
 * This is a singly linked list with no prev pointer.
 * @author Braga
 * @param <E>
 */
public class SinglyLinkedList<E> {
 
 Node<E> start;
 int size;
 
 public SinglyLinkedList(){
  start = null;
  size = 0;
 }
 
 //insertAtLast
 public void add(E data){
  insertAtLast(data);
 }
 
 public void insertAtLast(E data){
  if(size==0){
   start = new Node<E>();
   start.next = null;
   start.data = data;
  }else{
   Node<E> currentNode = getNodeAt(size-1);
   Node<E> newNode = new Node<E>();
   newNode.data = data;
   newNode.next = null;
   currentNode.next = newNode;
  }
  size++;
 }
 
 public void insertAtFirst(E data){
  if(size==0){
   start = new Node<E>();
   start.next = null;
   start.data = data;
  }else{
   Node<E> newNode = new Node<E>();
   newNode.data = data;
   newNode.next = start;
   start = newNode;
  }
  size++;
 }
 
 public Node<E> getNodeAt(int nodePos) throws ArrayIndexOutOfBoundsException{
  if(nodePos>=size || nodePos<0){
   throw new ArrayIndexOutOfBoundsException();
  }
  Node<E> temp = start;//Move pointer to front
  int counter = 0;
  for(;counter<nodePos;counter++){
   temp = temp.next;
  }
  return temp;
 }
 
 public void insertAt(int position, E data){
  if(position == 0){
   insertAtFirst(data);
  }else if(position==size-1){
   insertAtLast(data);
  }else{
   Node<E> tempNode = getNodeAt(position-1);
   Node<E> newNode = new Node<E>();
   newNode.data = data;
   newNode.next = tempNode.next;
   tempNode.next = newNode;
   size++;
  }
 }
 
 public Node<E> getFirst(){
  return getNodeAt(0);
 }
 
 public Node<E> getLast(){
  return getNodeAt(size-1);
 }
 
 public E removeAtFirst(){
  if(size==0){
   throw new ArrayIndexOutOfBoundsException();
  }
  E data = start.data;
  start = start.next;
  size--;
  return data;
 }
 
 public E removeAtLast(){
  if(size==0){
   throw new ArrayIndexOutOfBoundsException();
  }
  Node<E> tempNode = getNodeAt(size-2);
  E data = tempNode.next.data;
  tempNode.next = null;
  size--;
  return data;
 }
 
 public E removeAt(int position){
  if(position==0){
   return removeAtFirst();
  }else if(position == size-1){
   return removeAtLast();
  }else{
   Node<E> tempNode = getNodeAt(position-1);
   E data = tempNode.next.data;
   tempNode.next = tempNode.next.next;
   size--;
   return data;
  }
 }
 
 public int size(){
  return size;
 }
 
 public String toString(){
  if(size==0){
   return "";
  }else{
   StringBuilder output = new StringBuilder();
   Node<E> tempNode = start;
   while(tempNode.next!=null){
    output.append(tempNode.data).append(", ");
    tempNode = tempNode.next;
   }
   output.append(tempNode.data);
   return output.toString();
  }
 }
 
}
分享到:
评论

相关推荐

    SinglyLinkedLists

    单链表(Singly Linked List)是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的引用。在本主题中,我们将深入探讨单链表的"move to front"操作以及查找关键字(find keys...

    陈越、何钦铭-数据结构作业6:Reversing Linked List链表翻转

    Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→...

    Java Methods-Lists and Iterators.ppt

    列表可以是单链表(Singly-Linked List)、双链表(Doubly-Linked List)或循环链表(Circular List)。在 Java 语言中,列表通常使用链表实现。 单链表(Singly-Linked List) 单链表是一种链表,每个结点(Node...

    opcua库1.1.2.rar

    **opcua库1.1.2.rar** 是一个包含Open62541 OPC UA库的版本1.1.2的压缩包。Open62541是一个开源、跨平台的实现OPC统一架构(OPC Unified Architecture, OPC UA)标准的C库,用于设备间的安全、可靠和高效的数据交换...

    DSA-lab:数据结构和算法实验室资料库

    DSA实验室数据结构和算法实验室资料库结构 Lab 1: Introduction to GIT and the work-flow of the lab + starting with Singly Linked Lists作业1: 1.11.2 (额外功劳!) Lab 2: Circular Linked Lists and Doubly...

    Algorithms_and_Data_Structures_in_C++

    singly linked lists 126 M malloc 112 Mathematical Induction 42 Matrix adjacency 80 Median of three 152 Message in a hypercube 79 Message passing in a hypercube 78 Moveto 52 ...

    C语言程序设计-通讯录

    2. **单链表(Singly Linked Lists)**:虽然在提供的代码中并未直接使用链表,但在描述中提到了单链表,这暗示了可能通过链表实现动态内存分配和数据存储。链表是一种线性数据结构,每个节点包含数据和指向下一个...

    Algorithms in C++, Parts 1-4: Fundamentals, Data Structures, Sorting, Searching

    This chapter discusses different types of linked lists, such as singly and doubly linked lists, and their implementation in C++. 4. **Elementary List Processing**: Techniques for processing lists, ...

    Introduction to 64Bit Windows Assembly

    The chapter on data structures covers singly linked lists, doubly linked circular lists, hash tables and binary trees. Test programs are presented for all these data structures. There is a chapter on...

    LISTAS_ENLAZADAS

    在Java中,链表主要有两种实现:单链表(Singly Linked List)和双链表(Doubly Linked List)。 1. 单链表:每个节点只有一个指向下一个节点的引用。在Java中,可以使用`java.util.LinkedList`类来实现。这个类...

    GTK+ 1.2 Tutorial

    Singly Linked Lists Memory Management Timers String Handling Utility and Error Functions 22. GTK's rc Files Functions For rc Files GTK's rc File Format Example rc file 23. Writing Your Own Widgets ...

    功能强大的IOCP Socket Servre模块例程源码

    a、是否使用内核Singly-linked lists; b、是否使用处理线程(工作线程和处理线程分开); c、是否使用内核锁来同步链表。 8、可以实现集群服务器模式的通讯(有客户端socket); 9、可以单独设置每个连接的Data项来...

    Manage C data using the GLib collections – IBM Developer.pdf

    3. 单向链表(Singly-linked lists):每个节点只包含指向下一个节点的指针。 4. 哈希表(Hashtables):用于高效地查找、添加和删除键值对。 5. 动态字符串(Strings):可以动态增长的字符串类型。 6. 字符串块...

    Writing GNOME Applications

    Singly and Doubly Linked Lists 2-2. Structure of a Hash Table 2-3. Structure of an N-ary Tree 2-4. The GNOME Dependency Tree 2-5. GDK Event Flow 2-6. Widget Appearances 3-1. Running the configure ...

    Addison.Wesley.C++.by.Dissection.2002.pdf

    - **Example: A Singly Linked List:** Provides a linked list example. - **Strings Using Reference Semantics:** Explains reference semantics for strings. - **Constructor Issues and Mysteries:** ...

    数据结构(C#版)英文版

    - **单向链表(Singly Linked List)**:每个节点包含一个指向下一个节点的引用。 - **双向链表(Doubly Linked List)**:除了包含指向下一个节点的引用外,还包含指向前一个节点的引用。 - **循环链表(Circular ...

    WPTools.v6.29.1.Pro

    * allows changing of column width in redonly editors. Can be switchoed off in EditOptions or set compiler define TOTALREADONLY + wpDisableSelectAll in EditOptionsEx2 * changed reformat/repaint after...

    holbertonschool-low_level_programming

    专案0 * 1 * 2 * 3 * 4 *更多功能5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 *更多 13 * 预处理器14 * Structures_typedef 15 * Function_pointers 16 * Variadic_functions 17 *单链接列表18 * More_singly_linked_lists 。...

    LeetCode 算法题库学习(23)

    合并K个排序链表 题目描述: 解题思路: 第一种:这个方法比较暴力,思路也很简单。...# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class

Global site tag (gtag.js) - Google Analytics