在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Given a linked list, swap every two adjacent nodes and return its head. 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. 后面的逻辑就方便很多,不用判断这个那个。 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论