头插法、尾差法创建单链表及其合并
2015-07-04 14:52
281 查看
头插法图示:
尾差法图示:
代码:
尾差法图示:
代码:
package 数据结构; import java.util.Scanner; /** * 带头结点的链表的创建 * @author wky * */ class LNode{ int data; LNode next; } public class 链表操作 { //头插法创建链表 static LNode create_list_front(int n){ LNode head,p; head = new LNode(); head.next = null; for(int i=0;i<n;i++){ p = new LNode(); System.out.println("input elems(list_front):"); Scanner scn = new Scanner(System.in); p.data = scn.nextInt(); p.next = head.next; head.next = p; } return head; } //尾插法 static LNode create_list_rear(int n){ LNode s,r;//s指向新申请的节点,而r指向链表最新的终端节点 LNode head; head = new LNode(); head.next = null; r = head;//r指向head节点,此时head节点就是终端节点 for(int i=0;i<n;i++){ s = new LNode(); System.out.println("input elems(list_rear):"); Scanner scn = new Scanner(System.in); s.data = scn.nextInt(); r.next = s;//用r来接纳新的节点 r = r.next;//r指向终端节点 } r.next = null; return head; } //打印链表 static void print_list(LNode head){ LNode p; p = head.next; while(p!=null){ System.out.print(p.data+","); p = p.next; } } //两个有序链表合并 static LNode merge_list(LNode la,LNode lb,LNode lc){ LNode pa,pb,pc; pa = la.next; //pa,pb,pc 相当于一个跟踪标识号。 pb = lb.next; pc = lc; while((pa!=null)&&(pb!=null)){ if(pa.data<=pb.data){ pc.next = pa; pc = pc.next; pa = pa.next; }else{ pc.next = pb; pc = pc.next; pb = pb.next; } } pc.next = null; if(pa!=null) pc.next = pa; if(pb!=null) pc.next = pb; return lc; } public static void main(String[] args){ LNode la; LNode lb; LNode lc; lc = new LNode(); la = create_list_rear(5); lb = create_list_rear(6); lc = merge_list(la,lb,lc); System.out.println("l1:"); print_list(la); System.out.println("l2:"); print_list(lb); System.out.println("l3:"); print_list(lc); } }
相关文章推荐
- Binary search
- 正则表达式工具
- string赋值和操作
- HEAP CORRUPTION 错误的定位
- 实现单链表的逆置或叫翻转
- 【c语言】 模拟实现库函数的atoi函数
- 【前端】#001 编码规范
- 【计算机网络学习】之总述
- mysql主从复制(超简单)
- shell中的命令替换和变量替换
- c#上传文件(二)使用文件流保存文件
- 移动顿兼容以及测试常用网站
- git 版本回退之关于git reset --hard 和 --soft区别
- C++ 类中特殊的成员变量(常变量、引用、静态)的初始化方法 --转
- Python调用paramiko模块实现远程管理多台服务器
- 《Java课程实习》日志(周六)
- 黑马程序员---IO流
- 535 5.7.8 Error: authentication failed: generic failure安装EMOS时SMTP测试报错
- KMP算法详解
- 黑马程序员---正则表达式