题目描述

已知一个有序链表类LinkSortList及main函数的部分代码如下,请完成LinkSortList类的成员函数,得到对应的运行结果,勿改动main函数。
//有序表类
template
class LinkSortList
{
public:
LinkSortList( ); //建立只有头结点的空链表
~LinkSortList(); //析构函数
void Insert(T x); //在有序单链表中插入元素x使序列仍有序
int Length(); //求表长
int DeleteOdd(); //在单链表中删除所有奇数,返回值为奇数个数
void DispList( ); //遍历有序单链表,按序号依次输出各元素
private:
Node *first; //单链表的头指针
};
int main( ){
LinkSortList sa;
int x;
while(1)
{
cin>>x;
if(!x)break;
sa.Insert(x);
}
sa.DispList();
int count=sa.DeleteOdd();
cout<<”Count of deleted odds:”< sa.DispList();
return 0;
}

输入

输出

样例输入

42 5 32 56 34 7 233 1 0

样例输出

The length:8
The elements:1 5 7 32 34 42 56 233
Count of deleted odds:4
The length:4
The elements:32 34 42 56

提示

来源

提交

  1. import java.util.Scanner;
  2. class Node {
  3. public Object data;
  4. public Node next;
  5. public Node() {
  6. this(null,null);
  7. }
  8. public Node(Object data) {
  9. this(data,null);
  10. }
  11. public Node(Object data, Node next) {
  12. this.data = data;
  13. this.next = next;
  14. }
  15. }
  16. class LinkSortList{
  17. private Node head;
  18. public LinkSortList() {
  19. this.head = new Node();
  20. }
  21. public int length() {
  22. Node p = head.next;
  23. int length = 0;
  24. while(p!=null){
  25. p = p.next;
  26. ++length;
  27. }
  28. return length;
  29. }
  30. public void addByOrder(Node node){
  31. Node temp = head;
  32. boolean flag = false;
  33. while (true){
  34. if (temp.next==null){
  35. break;
  36. }
  37. else if ((int)temp.next.data>(int)node.data){
  38. break;
  39. }else if ((int)node.data == (int)temp.next.data){
  40. break;
  41. }else {
  42. temp = temp.next;
  43. }
  44. }
  45. node.next = temp.next;
  46. temp.next = node;
  47. }
  48. public void display() {
  49. System.out.println("The length:"+length());
  50. System.out.print("The elements:");
  51. Node node = head.next;
  52. while (node != null) {
  53. System.out.print(node.data + " ");
  54. node = node.next;
  55. }
  56. System.out.println();
  57. }
  58. public int deleteOdd(){
  59. int Odd = 0;
  60. Node node = head;
  61. while (node.next != null) {
  62. if((int)node.next.data%2!=0){
  63. node.next = node.next.next;
  64. Odd++;
  65. }else{
  66. node = node.next;
  67. }
  68. }
  69. return Odd;
  70. }
  71. }
  72. public class Main {
  73. public static void main(String[] args) {
  74. LinkSortList L = new LinkSortList();
  75. Scanner sc = new Scanner(System.in);
  76. while(sc.hasNext()){
  77. int d = sc.nextInt();
  78. if(d==0)break;
  79. try {
  80. L.addByOrder(new Node(d));
  81. } catch (Exception e) {
  82. e.printStackTrace();
  83. }
  84. }
  85. L.display();
  86. System.out.println("Count of deleted odds:"+L.deleteOdd());
  87. L.display();
  88. }
  89. }