给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
给定 1->2->3->4, 你应该返回 2->1->4->3.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create(h):
head=h;
for i in range(5):
p=ListNode(i);
h.next=p;
h=p;
h.next=None;
return head;
def reverse(h):
while h:
print(h.val);
h=h.next;
print('------------\n')
链表节点的交换
def swapPairs(self, head: ListNode) -> ListNode:
pre=ListNode(0);
h=pre;
利用开始交换节点的前一个节点
pre.next=head;
while pre.next and pre.next.next:
this=pre.next;
nex=this.next;
pre.next=nex;
k=nex.next;
nex.next=this;
this.next=k;
如果 pre=nex:相邻就交换
pre=this;
return h.next;
```python
def swapPairsForOne(self, head: ListNode) -> ListNode:
pre=ListNode(0);
h=pre;
利用开始交换节点的前一个节点
pre.next=head;
while pre.next and pre.next.next:
this=pre.next;
nex=this.next;
pre.next=nex;
k=nex.next;
nex.next=this;
this.next=k;
如果 pre=nex:相邻就交换
pre=nex;
return h.next;
```python
head=ListNode(-1);
head=create(head);
reverse(head);
head=swapPairsForOne(head);
reverse(head);
-1
0
1
2
3
4
------------
0
1
2
3
4
-1
------------