• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

LeetCodeOnlineJudge题目C#练习-SwapNodesinPairs

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

 1         public static LinkedListNode SwapNodesinPairs2(LinkedListNode head)
 2         {
 3             if (head == null || head.Next == null)
 4                 return head;
 5 
 6             LinkedListNode fakehead = new LinkedListNode();
 7             fakehead.Next = head;
 8 
 9             LinkedListNode l1 = head;
10             LinkedListNode l2 = head;
11             LinkedListNode prev = fakehead;
12             LinkedListNode ret = head.Next;
13             LinkedListNode next = head;
14             
15             while (next != null && next.Next != null)
16             {
17                 l1 = next;
18                 l2 = next.Next;
19                 next = next.Next.Next;
20                 l2.Next = l1;
21                 l1.Next = next;
22                 prev.Next = l2;
23                 prev = l1;
24             }
25 
26             return ret;
27         }

代码分析:

  看来我的总结是正确的,每遇到Linked List的题都在前面加个fakehead. 后面的逻辑就方便很多,不用判断这个那个。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Excel数据验重及Table数据验重发布时间:2022-07-10
下一篇:
C#简单的多线程发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap