翻转链表
来源:互联网 发布:股票模拟交易软件 编辑:程序博客网 时间:2024/06/15 23:40
翻转链表的两种情况
翻转单链表
很简单
public ListNode reverseList(ListNode head) { ListNode tmp=null; ListNode dummy=new ListNode(0); dummy.next=null; while(head!=null){ tmp=head.next; head.next=dummy.next; dummy.next=head; head=tmp; } return dummy.next; }
部分翻转链表
从部分位置翻转一个链表
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
记录要翻转部分链表的pre和start节点,然后用一个指针在要翻转的链表里遍历。
public ListNode reverseBetween(ListNode head, int m, int n) { if(head==null) return null; ListNode dummy=new ListNode(0); dummy.next=head; ListNode pre=dummy; for(int i=0;i<m-1;i++){ pre=pre.next; } ListNode start=pre.next; ListNode after=start.next; for(int i=0;i<n-m;i++){ start.next=after.next; after.next=pre.next; pre.next=after; after=start.next; } return dummy.next; }
两两翻转链表
给出 1->2->3->4, 你应该返回的链表是 2->1->4->3。
public ListNode swapPairs(ListNode head) { ListNode dummy=new ListNode(0); dummy.next=head; ListNode pre=dummy; while(pre.next!=null && pre.next.next!=null){ ListNode first=pre.next; ListNode second=pre.next.next; first.next=second.next; second.next=first; pre.next=second; pre=pre.next.next; } return dummy.next; }
阅读全文
0 0
- 无情链表的创建,,翻转翻转
- 链表翻转程序
- 链表翻转
- 链表翻转
- 链表翻转
- 翻转单向链表
- 翻转链表
- 原地翻转链表
- 链表的翻转
- 链表翻转
- 翻转部分链表
- 链表翻转
- 链表翻转
- c++翻转链表
- 翻转链表
- 链表翻转
- 翻转链表
- 链表翻转
- hdu 6156
- Python leetcode记录(1) -Two Sum
- 线程案例
- 最大的位或
- 炮仗的引线
- 翻转链表
- 爬虫_
- SpringMVC自定义格式化转换器
- UVa 11132 例题8-4 传说中的车(Fabled Rooks)
- Android仿IOS的Segmented Control 选项卡。
- extjs日期的转换
- c++中stringstream 类的用法及字符串与数字之间转化
- extern关键字
- Mac node已安装 但是报-bash: npm: command not found