单链表表示的两个数相加

本文介绍了一种高效算法,用于在单次遍历中删除单链表的倒数第N个节点。通过双指针技巧,先让一指针前进N步,再同时移动两个指针直至前指针到达链表尾部,从而定位并删除目标节点。

参考derrantcm的博客,网址:https://blog.youkuaiyun.com/derrantcm/article/details/46905467

 

package algorithm;

import java.util.LinkedList;
import java.util.List;


/*
移除单链表的倒数第N个节点

原题
  Given a linked list, remove the nth node from the end of list and return its head. 
  For example,
   Given linked list: 1->2->3->4->5, and n = 2.
   After removing the second node from the end, the linked list becomes 1->2->3->5.

  Note: 
  Given n will always be valid. 
  Try to do this in one pass. 
题目大意
  删除单链表的倒数第N个结点,注意:输入的N都是合法,在一次遍历中完成操作。 
解题思路
  先让一个指针走找到第N个节点,然后再让一个指针指向头结点,然后两具指针一起走,直到前一个指针直到了末尾,后一个指针就是倒数第N+1个结点,删除倒数第N个结点就可以了。 
*/

public class RemoveNthNumFromEnd {


static class Node{
    int value;
    Node nextNode;
    
    public Node(int value){
        this.value=value;
        this.nextNode=null;

    }
    
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public Node getNextNode() {
        return nextNode;
    }
    public void setNextNode(Node nextNode) {
        this.nextNode = nextNode;
    }
    
}

    public static Node makeListNode(int[] nums){
        Node listNode=null;
        Node pre=null;
        for(int i=0;i<nums.length;i++){
            Node node=new Node(nums[i]);
            if(listNode==null){
                listNode=node;
                pre=node;
            }else{
                pre.nextNode=node;
                pre=pre.nextNode;
            }
        }
        
        return listNode;
        
    }
    
    public static void printList(Node listNode){
      if(listNode==null)
          return;
      System.out.println();
      int value=listNode.getValue();
      System.out.print(value);
      Node node=listNode.getNextNode();
      while(node!=null){
          value=node.getValue();
          System.out.print(","+value);
          node=node.getNextNode();
          
      }
      
      System.out.println();
      
    }
    

    public static int getNodeListCount(Node listNode){
      if(listNode==null)
          return 0;
      int result=1;
      Node node=listNode.getNextNode();
      while(node!=null){
          
          node=node.getNextNode();
          result++;
      }
      return result;
    }
    
    //删除倒数第n个数
    public static Node removeNthFromEnd(Node node,int n){
        
        if(node==null){
            return null;
        }
        int count=getNodeListCount(node);
        System.out.println("Node的数量="+count);
        
        int deleteNum=count-n+1; //需要删除的第几个元素
        
        Node pa=node;
        Node pb=node;
        //遍历第几个数
        for(int i=0;i<deleteNum-2&&pa!=null;i++){
            pa=pa.nextNode;
            
        }
        
        System.out.println(deleteNum);
        if(deleteNum==1){
            //删除第一个节点
            pa=pa.nextNode;
            return pa;
        }else if(deleteNum>1){
            //删除该节点
            pa.nextNode=pa.nextNode.nextNode;
            return node;
        }else{
            
        }
        
      return pa;
        
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] nums={1,2,3,4,5};
        Node node=makeListNode(nums);

        printList(node);
        
        Node node1=removeNthFromEnd(node,1);
        //printList(node);//原始数据
        printList(node1);        //删除后数据
    }

}
 

可以按照以下步骤实现: 1. 定义一个有序单链表结构体,包含个成员变量:系数和指数。 2. 分别输入个多项式的系数和指数,将它们按照指数从大到小的顺序插入到有序单链表中。 3. 定义一个新的有序单链表,用于存储相加后的多项式。 4. 遍历个有序单链表,将相同指数的项相加,将结果插入到新的有序单链表中。 5. 如果有一个有序单链表已经遍历完了,将另一个有序单链表中剩余的项插入到新的有序单链表中。 6. 输出新的有序单链表中的项,即为相加后的多项式。 以下是示例代码: ```c #include <stdio.h> #include <stdlib.h> // 定义有序单链表结构体 typedef struct node { int coef; // 系数 int exp; // 指数 struct node *next; } Node; // 插入节点到有序单链表中 void insert(Node **head, int coef, int exp) { Node *new_node = (Node *)malloc(sizeof(Node)); new_node->coef = coef; new_node->exp = exp; new_node->next = NULL; if (*head == NULL || exp > (*head)->exp) { new_node->next = *head; *head = new_node; } else { Node *cur = *head; while (cur->next != NULL && exp < cur->next->exp) { cur = cur->next; } new_node->next = cur->next; cur->next = new_node; } } // 释放有序单链表的内存 void free_list(Node *head) { Node *cur = head; while (cur != NULL) { Node *temp = cur; cur = cur->next; free(temp); } } // 打印有序单链表中的项 void print_list(Node *head) { Node *cur = head; while (cur != NULL) { printf("%dx^%d ", cur->coef, cur->exp); cur = cur->next; } printf("\n"); } // 个多项式相加 Node *add_poly(Node *poly1, Node *poly2) { Node *result = NULL; while (poly1 != NULL && poly2 != NULL) { if (poly1->exp > poly2->exp) { insert(&result, poly1->coef, poly1->exp); poly1 = poly1->next; } else if (poly1->exp < poly2->exp) { insert(&result, poly2->coef, poly2->exp); poly2 = poly2->next; } else { int sum = poly1->coef + poly2->coef; if (sum != 0) { insert(&result, sum, poly1->exp); } poly1 = poly1->next; poly2 = poly2->next; } } while (poly1 != NULL) { insert(&result, poly1->coef, poly1->exp); poly1 = poly1->next; } while (poly2 != NULL) { insert(&result, poly2->coef, poly2->exp); poly2 = poly2->next; } return result; } int main() { // 输入第一个多项式 printf("Enter the first polynomial:\n"); Node *poly1 = NULL; int coef, exp; do { printf("Enter coefficient and exponent (enter 0 0 to stop): "); scanf("%d %d", &coef, &exp); if (coef != 0) { insert(&poly1, coef, exp); } } while (coef != 0 || exp != 0); // 输入第二个多项式 printf("Enter the second polynomial:\n"); Node *poly2 = NULL; do { printf("Enter coefficient and exponent (enter 0 0 to stop): "); scanf("%d %d", &coef, &exp); if (coef != 0) { insert(&poly2, coef, exp); } } while (coef != 0 || exp != 0); // 输出个多项式 printf("First polynomial: "); print_list(poly1); printf("Second polynomial: "); print_list(poly2); // 计算相加后的多项式 Node *result = add_poly(poly1, poly2); // 输出相加后的多项式 printf("Result: "); print_list(result); // 释放内存 free_list(poly1); free_list(poly2); free_list(result); return 0; } ``` 如果您有任何问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值