Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class People{
- public static void main (String[] args) {
- Scanner scnr = new Scanner(System.in);
- PeopleNode headNode;
- PeopleNode currNode;
- PeopleNode lastNode;
- String people;
- int numberOfpeople;
- int i;
- // Front of nodes list
- headNode = new PeopleNode();
- lastNode = headNode;
- int input = scnr.nextInt();
- for(i = 0; i < input; i++ ) {
- people = scnr.next();
- numberOfpeople=scnr.nextInt();
- currNode = new PeopleNode(people, numberOfpeople);
- currNode.insertAtFront(headNode, currNode);
- lastNode = currNode;
- }
- // Print linked list
- currNode = headNode.getNext();
- while (currNode != null) {
- currNode.printNodeData();
- currNode = currNode.getNext();
- }
- }
- }
- public class PeopleNode {
- private String People;
- private int numberOfPeople;
- private PeopleNode nextNodeRef; // Reference to the next node
- public PeopleNode() {
- People = "";
- numberOfPeople = 0;
- nextNodeRef = null;
- }
- // Constructor
- public PeopleNode(String people, int numberOfPeople) {
- this.People= people;
- this.numberOfPeople = numberOfPeople;
- this.nextNodeRef = null;
- }
- // Constructor
- public PeopleNode(String People, int numberOfPeople, PeopleNode nextLoc) {
- this.People= People;
- this.numberOfPeople = numberOfPeople;
- this.PeopleNode= nextLoc;
- }
- //Define an insertAtFront() method that inserts a node at the
- //front of the linked list
- public void insertAtFront(PeopleNode headNode,PeopleNode currNode) {
- PeopleNode tmpNext;
- tmpNext = this.nextNodeRef;
- this.nextNodeRef = currNode;
- currNode.nextNodeRef = tmpNext;
- }
- // Get location pointed by nextNodeRef
- public PeopleNode getNext() {
- return this.nextNodeRef;
- }
- // Print node data
- public void printNodeData() {
- System.out.println(this.numberOfPeople + " " + this.People);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement